What you’ll get
Work out how long a 4.7 GB disk image takes to download on a 100 Mbit/s plan. Give the values names, and the formula reads in words:
# download.py
size_gb = 4.7 # disk image, GB
speed_mbit = 100 # plan, Mbit/s
seconds = size_gb * 1000 * 8 / speed_mbit
print("Downloads in", seconds / 60, "min")
python download.py
# Downloads in 6.266666666666667 min
The gigabytes here are the ISP’s, decimal: 1 GB is 1000 MB, a byte is 8 bits. The plan changed to 500 Mbit/s — change
one line, speed_mbit = 500, and the formula stays. The extra decimal places go away in the Strings chapter.
How it works: a name is a label on a value
= in Python isn’t equality but “name it”: compute the value on the right, write on the left the name you’ll use to get
it later. That’s why x = x + 1 isn’t a contradiction: take the value of x, add 1, and move the name onto the result.
size_gb ──► 4.7 float
speed_mbit ──► 100 int
seconds ──► 376.0 float
The value lives in memory on its own, and the type is its. A name has no type: you can move it onto a value of a different type, and Python won’t object.
value = 100
print(type(value)) # <class 'int'>
value = "one hundred"
print(type(value)) # <class 'str'>
In a short script that saves lines; in a long one it hides a bug: a name that was a number three screens up is now a string, and you find out only at run time, on the line that does something with it.
The type decides what a value can do
+ adds numbers and joins strings, and Python won’t add a number to a string at all — it doesn’t guess what you meant.
| Type | Example | What it is |
|---|---|---|
int |
100, -3, 2 ** 64 |
an integer of any length |
float |
4.7, 6.0, 1e-3 |
a fraction; computed with rounding error — the Numbers chapter |
str |
"100", 'Downloads' |
a string: text in quotes, single or double |
bool |
True, False |
yes or no; a comparison answers this way: speed_mbit > 50 is True |
NoneType |
None |
“no value”: a function without return returns it |
type() shows a value’s type:
>>> type(4.7)
<class 'float'>
>>> type("4.7")
<class 'str'>
>>> 4.7 * 2
9.4
>>> "4.7" * 2
'4.74.7'
A function named after a type converts to it:
| Code | Result | What it does |
|---|---|---|
int("100") |
100 |
a string of digits into an integer |
float("4.7") |
4.7 |
a string into a fraction |
str(100) |
"100" |
a number into a string |
int(4.7) |
4 |
a fraction into an integer: drops the tail rather than rounding; int(-4.7) is -4 |
int("4.7") |
ValueError |
int doesn’t read a fraction in a string: use float first |
Keyboard input is always a string
input() prints a question, waits for what’s typed, and returns it as a string — even if it’s digits. Without
converting to a number, the script crashes:
size_gb = input("Size, GB: ")
seconds = size_gb * 1000 * 8 / 100
# TypeError: unsupported operand type(s) for /: 'str' and 'int'
The error is on the division, though the multiplication came first: "4.7" * 1000 is the string 4.7 a thousand times
in a row, and Python can repeat a string. It can’t divide one. Convert right at input:
size_gb = float(input("Size, GB: "))
speed_mbit = float(input("Speed, Mbit/s: "))
print("Downloads in", size_gb * 1000 * 8 / speed_mbit / 60, "min")
python download.py
# Size, GB: 4.7
# Speed, Mbit/s: 100
# Downloads in 6.266666666666667 min
Which names are allowed
- Latin letters, digits and
_, not starting with a digit:speed_mbit,size2.2size = 5givesSyntaxError: invalid decimal literal. - Case matters:
Speedandspeedare two different names. - Lowercase with
_between words — that’s the Python convention (PEP 8):speed_mbit, notspeedMbit. - The unit in the name, if there is one:
size_gbis clearer a week later thansizeors. - Non-ASCII letters work:
größe = 5is a valid line. But you won’t meet them in other people’s code, and others may not be able to type them, so stick to ASCII. - Language keywords are taken:
class,for,if,defgiveSyntaxError. Built-in function names —print,input,type— are taken implicitly: Python acceptsprint = 5, and the nextprint(…)breaks.
Take it further
A byte is 8 bits: divide megabits by 8.
speed_mbit = 100
print(speed_mbit / 8, "MB/s")
# 12.5 MB/sThe example’s task reversed: speed × seconds gives megabits; divide by 8 for megabytes, by 1000 for gigabytes.
speed_mbit = 100
seconds = 60 * 60
print(speed_mbit * seconds / 8 / 1000, "GB")
# 45.0 GBprint("Speed: " + speed_mbit) two waysYou can only join a string with a string. Or don’t join at all: print puts a space between parts itself.
speed_mbit = 100
print("Speed:", speed_mbit)
print("Speed: " + str(speed_mbit))If it doesn’t work
NameError: name 'speed' is not defined
- Cause
- A typo in the name, or the name was used before it was assigned. In interactive mode, a variable from a previous session: after
exit()everything is forgotten. - Fix
- The name letter for letter, with the same case; the assignment higher up the file than the first use.
TypeError: can only concatenate str (not "int") to str
- Cause
- Concatenating a string with a number:
"Speed: " + 100. - Fix
- Pass the parts to
printseparated by commas —print("Speed:", 100)— or turn the number into a string:"Speed: " + str(100).
TypeError: unsupported operand type(s) for /: 'str' and 'int'
- Cause
- The value from
input()stayed a string: multiplication repeated the string, and Python can’t divide a string. - Fix
- Convert right at input:
float(input("Size, GB: ")).
ValueError: could not convert string to float: '4,7'
- Cause
- The decimal was typed with a comma, as many locales write it, and Python expects a point.
- Fix
- Type
4.7. In a script for others, replace the comma before converting:float(text.replace(",", ".")); string methods are in the Strings chapter.
TypeError: 'int' object is not callable
- Cause
- A variable was named after a built-in function —
print = 5orinput = …— and the name now leads to a number. - Fix
- Rename the variable. In interactive mode,
del printbrings back the built-inprint.