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
| Type | Holds | Examples | Convert with |
|---|---|---|---|
| int | whole numbers, positive or negative | 326, -4, 0 | int("42") gives 42; int(7.9) gives 7 (cuts, does not round) |
| float | numbers with a decimal point | 326.2, 0.5, 1.609 | float("7.2") gives 7.2 |
| str | text between quotes | "Hello.", 'BIS', "" | str(3.5) gives "3.5" |
| bool | True or False | True, 5 > 3 | bool(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".
"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
| Expression | Result | Why |
|---|---|---|
19 / 4 | 4.75 | ordinary division always gives a float |
20 / 4 | 5.0 | still a float, even when it divides exactly |
19 // 4 | 4 | floor division: how many whole times 4 fits |
19 % 4 | 3 | modulo: the remainder after floor division |
-7 // 2 | -4 | floor means rounding down, towards minus infinity |
5 ** 2 | 25 | power |
2 + 3 * 2 ** 2 | 14 | power first, then *, then + |
round(3.14159, 2) | 3.14 | round 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.
Minutes to hours and minutes
A meeting lasts 135 minutes. Write it as hours and minutes.
Whole hours
Remaining minutes
Check
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:
| Method | Example | Result |
|---|---|---|
| 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.
All cards known
Reset the progress or pick another unit to keep practising.
Multiple choice (9)
What does print(7 / 2, 7 // 2, 7 % 2) print?
x = input("Number: ") and the user types 4. What is x * 2?
With s = "Business", what is s[-3:]?
Which expression gives the last digit of the whole number n?
What is the type of 10 / 5?
What does "VUB".lower() * 2 give?
Which statement converts the text "3.5" into a number?
What is printed by print("a", "b", sep="")?
What does round(7.456, 1) give?
Exam-style open questions (2)
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.
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.