hanegreefs.com/Business Information SystemsBIS
Python 1 · unit 4 of 16

Data types, operators and strings

Your first Python programs: the four basic types, variables and assignment, arithmetic with / and // and %, input and output with type conversion, and strings with indexing, slicing and methods.

Based on: lecture 4 (Python in a nutshell) and exercise session WPO2 (data types and operators) · About 60 minutes

From algorithm to PythonImportant

Python is the language of the practical half of the course. In the eight steps of programming it is step 4, coding: you translate the pseudo code of step 3 line by line. Read becomes input(), Write becomes print(), and the arrow of the assignment becomes =.

mile = float(input("Give distance in miles: "))
km = mile * 1.609
print(mile, "miles =", km, "kilometre")

Three details matter from the very first program. input() always returns a string, so you convert it with int() or float() before you calculate. print() with commas puts one space between the values. And a line starting with # is a comment: Python ignores it.

You can practise every example of this unit in the coding lab: your code runs inside your own browser, not on a server.

Four basic types and variablesImportant

TypeHoldsExamplesConvert with
intwhole numbers, positive or negative326, -4, 0int("42") gives 42; int(7.9) gives 7 (cuts, does not round)
floatnumbers with a decimal point326.2, 0.5, 1.609float("7.2") gives 7.2
strtext between quotes"Hello.", 'BIS', ""str(3.5) gives "3.5"
boolTrue or FalseTrue, 5 > 3bool(0) is False, bool("") is False, any other number or text is True

A variable is a name that refers to a value. Choose names that describe the value (rectangle_width, not x); names are case sensitive and cannot start with a digit. Python is untyped: you do not declare a type, and type(value) tells you what Python decided.

Several variables can be assigned at once: a, b, c = 42, 7, 16.2. The short forms a += 2, a -= 2, a *= 2 and so on mean "take the old value, apply the operator, store the result".

Common trap"5" + "3" gives "53", not 8: the plus sign glues strings together. And "5" + 3 gives a TypeError. Convert first: int("5") + 3.

Arithmetic that surprises beginnersImportant

ExpressionResultWhy
19 / 44.75ordinary division always gives a float
20 / 45.0still a float, even when it divides exactly
19 // 44floor division: how many whole times 4 fits
19 % 43modulo: the remainder after floor division
-7 // 2-4floor means rounding down, towards minus infinity
5 ** 225power
2 + 3 * 2 ** 214power first, then *, then +
round(3.14159, 2)3.14round to two decimals

Modulo is the workhorse of exam exercises: n % 2 == 0 tests whether a number is even, n % 10 gives the last digit and n // 10 removes it, and total_minutes // 60 and total_minutes % 60 split minutes into hours and minutes.

Worked example

Minutes to hours and minutes

A meeting lasts 135 minutes. Write it as hours and minutes.

1

Whole hours

135 // 60 = 2
2

Remaining minutes

135 % 60 = 15
3

Check

2 × 60 + 15 = 135
Answer

The program prints 2 h 15 min. This is exercise b4 in the coding lab.

Strings: indexing, slicing and methodsImportant

A string is a sequence of characters. Positions (indexes) start at 0; negative indexes count from the end, so -1 is the last character. A slice s[a:b] takes positions a up to but not including b; a missing a means "from the start", a missing b means "to the end", and a third number is the step.

With s = "Hello."Result
s[0]"H"
s[-1]"."
s[1:3]"el"
s[3:]"lo."
s[:4]"Hell"
s[::-1]".olleH" (reversed)
len(s)6
s[6]IndexError: there is no position 6

Strings cannot be changed in place (they are immutable); every method returns a new string. The ones you meet most:

MethodExampleResult
upper, lower, title, capitalize"happy new year".title()"Happy New Year"
strip" hi \n".strip()"hi" (spaces and newlines removed at both ends)
count, find"Happy".count("p"), "Happy".find("y")2 and 4 (find gives -1 when absent)
replace"New Year".replace("New", "Old")"Old Year"
split, join"A:B:C".split(":"), "-".join(["a","b"])["A", "B", "C"] and "a-b"
startswith, isnumeric"911".isnumeric()True
format"{:.2f}".format(3.14159)"3.14"

Membership works with in: "lick" in "click" is True. Strings can be repeated with *: "ab" * 3 is "ababab". Inside quotes, \n is a new line and \t a tab.

Input and output in practiceNeutral

A user-friendly program says what it expects: put the question inside input("Give the width: "). To build one line out of several parts you can use commas (spaces added automatically), the plus sign (only strings, no spaces), the sep and end options of print, or format.

name = input("Your name: ")
age = int(input("Your age: "))
print("Hello", name, "you will be", age + 1, "next year")
print("Total: " + str(age * 12) + " months")
print("a", "b", "c", sep="-")

With inputs Ann and 19 this prints Hello Ann you will be 20 next year, then Total: 228 months, then a-b-c.

Key takeaways

  • input() returns a string: convert with int() or float() before calculating.
  • / always gives a float; // is floor division and % the remainder.
  • Indexes start at 0, s[-1] is the last character, s[a:b] stops before b.
  • Strings are immutable: methods return a new string.
  • Plus joins strings, commas in print add spaces, str() turns numbers into text.

Loading cards
Question
Click, tap or press space to flip
Answer

Multiple choice (9)

Question 1 · Python 1

What does print(7 / 2, 7 // 2, 7 % 2) print?

Why: / gives a float, // the whole part, % the remainder.
Question 2 · Python 1

x = input("Number: ") and the user types 4. What is x * 2?

Why: x is the string "4"; a string times 2 repeats it.
Question 3 · Python 1

With s = "Business", what is s[-3:]?

Why: The last three characters.
Question 4 · Python 1

Which expression gives the last digit of the whole number n?

Why: The remainder after division by 10 is the last digit.
Question 5 · Python 1

What is the type of 10 / 5?

Why: Ordinary division always gives a float: 2.0.
Question 6 · Python 1

What does "VUB".lower() * 2 give?

Why: lower first, then the string is repeated.
Question 7 · Python 1

Which statement converts the text "3.5" into a number?

Why: int("3.5") gives a ValueError; float works.
Question 8 · Python 1

What is printed by print("a", "b", sep="")?

Why: sep="" removes the space between the values.
Question 9 · Python 1

What does round(7.456, 1) give?

Why: Rounded to one decimal.

Exam-style open questions (2)

Open question · Python 1

Seconds to time

Write a program that reads a number of seconds and prints it as hours, minutes and seconds, for example 3725 becomes 1 h 2 min 5 s. Explain which operators you use.

Show a model answer outline
  • Read with int(input(...)).
  • hours = s // 3600; rest = s % 3600.
  • minutes = rest // 60; seconds = rest % 60.
  • Check: 3600 + 120 + 5 = 3725.
Open question · Python 1

Name formatter

Write code that turns " ann DE smet " into "Ann De Smet" and also prints the initials "A.D.S.". Name the methods you use.

Show a model answer outline
  • strip() removes outer spaces; title() capitalises each word.
  • split() gives the words; take word[0] of each.
  • Join the initials with "." and add a final dot, or loop and build the string.

LabCoding lab: first programs

Pick an exercise, write your code and press Run tests. Your code runs in a locked sandbox inside your own browser; nothing is sent anywhere.

LabString index and slice explorer

Positions start at 0 and the stop position is not included. Negative numbers count from the end.