Arithmetic operators
Operators are the symbols that do work on values: + adds, * multiplies, and so on.
Arithmetic operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | addition | 7 + 2 | 9 |
- | subtraction | 7 - 2 | 5 |
* | multiplication | 7 * 2 | 14 |
/ | division | 7 / 2 | 3.5 |
// | floor division | 7 // 2 | 3 |
% | remainder (modulo) | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
Python
print(7 + 2, 7 - 2, 7 * 2)
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(7 ** 2)Floor division and remainder
// divides and rounds down to a whole number; % gives what is left over. Together they answer questions like "how many whole hours, and how many minutes left?":
Python
total_minutes = 135
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{hours} h {minutes} min")% is also the standard way to test divisibility: n % 2 == 0 means n is even.
Python
for n in [10, 7, 0, 15]:
print(n, "is even" if n % 2 == 0 else "is odd")Order of operations
Python follows the usual maths rules: brackets first, then powers, then * / // %, then + -.
Python
print(2 + 3 * 4) # 14, not 20
print((2 + 3) * 4) # 20
print(2 ** 3 ** 2) # powers go right to left: 2 ** 9 = 512
print(-3 ** 2) # -(3 ** 2) = -9When in doubt, add brackets. They cost nothing and make the meaning obvious.
Assignment shorthands
Updating a variable using its own value is so common that Python has shortcuts:
| Shorthand | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 5 | x = x * 5 |
x /= 5 | x = x / 5 |
x //= 5 | x = x // 5 |
x %= 5 | x = x % 5 |
x **= 5 | x = x ** 5 |
Python
score = 10
score += 5
score *= 2
print(score)Python has no ++ operator; write x += 1.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.