Python, lesson 3
Programs become useful when they react to data. The simplest way to get data into a Python
program is input(). It reads one line from standard input and hands it back as a string,
with the trailing newline already removed.
Each call reads the next line. If there are no lines left, input() raises an EOFError,
so only call it as many times as there are lines to read.
input() always returns a str, even if the user typed digits. To do maths you convert it:
int() and float() ignore spaces around the number, so " 42 " is fine. Text like
passed to , or passed to either, raises a . You'll learn to handle
that in the lesson on errors.
2 exercises to try what you just read.
"4.5"int()"ten"ValueErrorWhen several numbers share one line, split the line first. split() with no argument breaks
on any run of spaces and gives you a list of strings:
map(int, ...) applies int to every piece, and the two names on the left unpack the result.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
// | floor division | 7 // 2 | 3 |
% | remainder | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
Two things surprise people coming from other languages:
/ always gives a float, even for 8 / 4 (that's 2.0). Use // when you want a
whole number.// rounds down, toward minus infinity, so -7 // 2 is -4, not -3.divmod(a, b) gives you both answers at once as a pair: divmod(130, 60) is (2, 10).
That's perfect for turning minutes into hours and minutes.
The usual precedence rules apply: ** first, then *, /, //, %, then + and -.
Use parentheses whenever the order isn't obvious to a human reader.
Python's integers have no size limit, so 2 ** 200 just works. Floats are approximations, so
0.1 + 0.2 prints 0.30000000000000004. That's normal for every language that uses binary
floating point.
total += 5 means total = total + 5. The same pattern works for -=, *=, /=, //= and %=.
To show money or measurements neatly, use a format spec in an f-string. :.2f means "a float
with exactly two digits after the point":
This rounds only the displayed text; the variable keeps its full value.
Friends share a restaurant bill equally. The first line is the bill total (it may have decimals), the second line is the number of people. Print how much each person pays with exactly two digits after the decimal point.
Sample input:
Sample output:
Streaming apps show running times like 2 h 10 min. Read a whole number of minutes and print
it in exactly that form: hours, a space, h, a space, minutes, a space, min.
Sample input:
Sample output:
name = input()
print(f"Hi, {name}!")age = int(input()) # "29" -> 29
height = float(input()) # "1.75" -> 1.75a, b = input().split() # "3 4" -> "3", "4"
a, b = int(a), int(b)
x, y = map(int, input().split()) # the same thing in one lineshare = 10 / 3
print(f"{share:.2f}") # 3.33100
333.331302 h 10 min