Operator precedence
| Rank | Operators | Groups |
|---|
| 1 (first) | ( ) | inside out |
| 2 | ** | right to left |
| 3 | * / // % | left to right |
| 4 (last) | + - | left to right |
Careful: A minus sign in front of a number ranks below **, so -2 ** 2 is −4. Write (-2) ** 2 to square −2. ^ is not a power in Python.
Taught in Arithmetic and precedence
Division, floor division and remainder
Also called integer division, modulo, mod.
a // b full groups of b fit in a, with a % b left over: 17 // 5 is 3 boxes and 17 % 5 is 2 eggs left.
7 / 2 # 3.5, always a float
7 // 2 # 3, rounds down
7 % 2 # 1, the remainder
-7 // 2 # -4, down, not toward 0
Careful: / gives a float even for an even division: 6 / 2 is 3.0. Floor division rounds down, so it differs from cutting off the decimals for negative numbers.
Taught in Three kinds of division
Types of values
type(x) names the type: print(type(3.0)) shows <class 'float'>.
| Type | Examples | Made by |
|---|
int | 42, -7, 0 | whole numbers; //, %, ** on ints |
float | 42.0, 0.5, 4e2 | a decimal point or e; any / |
str | "42", "hello" | quotes |
Taught in Types: int, float and str
Strings with + and *
"3" + "4" # "34", joined
"-" * 20 # 20 dashes, repeated
"3" + 4 # TypeError
Careful: + can join two strings or add two numbers, never one of each.
Taught in Types: int, float and str
Float precision and scientific notation
Also called floating point error, e notation.
A float keeps about 16 significant digits; most decimals are stored slightly off, so 0.1 + 0.2 is 0.30000000000000004. Halves and quarters are exact. Ints are exact at any size. 6.02e23 is 6.02 × 10²³ and 1e-6 is one millionth; a number written with e is a float.
Careful: Don't test computed floats with ==: 0.1 + 0.2 == 0.3 is False. Keep money as whole cents in ints.
Taught in Floats are close, not exact
print with several values
Commas separate the arguments; print puts sep (a space by default) between them and end (a new line by default) after the last. # starts a comment.
print("Mass:", 2.5, "kg") # Mass: 2.5 kg
print(1, 2, 3, sep="-") # 1-2-3
print("A", end="") # no new line
Taught in Several values on one line
Reading a traceback
Also called error message.
Read the last line first, then the line number above it.
| Last line | Usual cause |
|---|
SyntaxError | a missing quote, comma or bracket; nothing runs |
NameError | a word without quotes, or a misspelled name |
TypeError | an operator given the wrong type, such as "3" + 4 |
Careful: The line named is where Python noticed the problem; the mistake can be on an earlier line.
Taught in Reading your first error message