Operators & Precedence
beginner12 min readLesson 7 of 169
Arithmetic, division flavors, comparisons, boolean logic, and precedence.
Arithmetic
| Operator | Does | Example |
| --- | --- | --- |
| + - * | add, subtract, multiply | 2 * 3 โ 6 |
| / | true division (always float) | 7 / 2 โ 3.5 |
| // | floor division (drops remainder) | 7 // 2 โ 3 |
| % | modulo (remainder) | 7 % 2 โ 1 |
| ** | power | 2 ** 10 โ 1024 |
// and % are a pair: how many whole times does 2 fit into 7 (3), and what
is left over (1). Even/odd checks, cycling through positions, splitting items
into groups โ modulo is everywhere.
Comparison operators
age == 18 # equals (two signs โ one sign is assignment!)
age != 18 # not equals
age < 18 # less than
age >= 18 # greater or equal
Comparisons produce booleans: True or False.
Combining conditions
age >= 13 and age <= 19 # both must hold
day == "sat" or day == "sun"
not is_empty
Precedence
** beats * / // % which beat + -; parentheses win over everything:
2 + 3 * 4 # 14 โ not 20
(2 + 3) * 4 # 20
Augmented assignment
score += 5 # same as score = score + 5
count -= 1
name *= 2