Sub topic 6
Arithmetic operators and precedence
This chapter assumes you can run Python code, print values, and know that an int is a whole number and a float has a decimal point. It covers Python's arithmetic operators, the result type each one produces, and the rules that decide the order of evaluation in a longer expression. Rounding error in floats and Decimal are covered in a later chapter.
The operators
Python has seven arithmetic operators for numbers.
| Operator | Name | Example | Result |
|---|---|---|---|
| `+` | addition | `7 + 2` | `9` |
| `-` | subtraction | `7 - 2` | `5` |
| `*` | multiplication | `7 * 2` | `14` |
| `/` | true division | `7 / 2` | `3.5` |
| `//` | floor division | `7 // 2` | `3` |
| `%` | modulo (remainder) | `7 % 2` | `1` |
| `**` | exponentiation | `7 ** 2` | `49` |
Two more operators are unary, meaning they take one operand: -x negates and +x returns the value unchanged.
print(7 / 2)
print(7 // 2)
print(-7 // 2)
print(-7 % 2)
print(2 ** 10)This prints 3.5, 3, -4, 1, and 1024. The -4 and 1 are the results that surprise people, and the next sections explain them.
What type comes out
The result type follows fixed rules:
+,-,*,//,%, and**on two ints give an int. If either operand is a float, the result is a float./always gives a float, even when the division is exact.6 / 3is2.0, not2.**with an int base and a negative int exponent gives a float, because the result is a fraction:2 ** -1is0.5.
print(6 / 3)
print(type(6 / 3))
print(7.5 // 2)
print(5 + 2.0)
print(2 ** -1)
print(2 ** 100)Python ints have no fixed size, so 2 ** 100 prints 1267650600228229401496703205376 with no overflow. Floats are limited to about 15 to 17 significant digits.
Floor division and modulo are a pair
// rounds the quotient down toward negative infinity. It does not truncate toward zero. That is why -7 // 2 is -4: the exact quotient is -3.5, and the next integer below it is -4.
% is defined so that the following identity always holds:
a == (a // b) * b + a % bFor -7 and 2, we have -4 * 2 + 1 == -7, so -7 % 2 must be 1. The remainder takes the sign of the divisor, which is the opposite of C, Java, and JavaScript. With a positive divisor, % is never negative. This makes it safe for wrapping around a range:
print((10 + 5) % 12)
print((-1) % 7)
print(10 % -3)
print(7.5 // 2)
print(-7.5 % 2)This prints 3, 6, -2, 3.0, and 0.5. Floor division and modulo also work on floats, but the result of // is a float with a whole-number value.
When you need both parts of a division, divmod(a, b) returns (a // b, a % b) in one call:
total_minutes = 135
hours, minutes = divmod(total_minutes, 60)
print(hours, minutes)
print(divmod(-7, 2))The output is 2 15 and then (-4, 1).
Exponentiation
** raises the left operand to the power of the right operand. Two details matter:
- It is right-associative.
2 ** 3 ** 2means2 ** (3 ** 2), which is512, not64. - It binds tighter than a unary minus on its left.
-2 ** 2means-(2 ** 2), which is-4. Write(-2) ** 2for4.
On the right side, a unary minus binds first, so 2 ** -1 is valid and equals 0.5.
Fractional exponents work for roots: 9 ** 0.5 is 3.0. A negative base with a fractional exponent, such as (-8) ** (1 / 3), returns a complex number in Python 3 instead of raising an error. If you expected a real number, use math.cbrt (Python 3.11+) or check the sign of the input yourself.
Precedence and associativity
When an expression has several operators, Python uses two rules. Precedence decides which operator runs first. Associativity decides the order when operators share a level. Most binary operators are left-associative, so they group left to right.
| Level (highest first) | Operators | Grouping |
|---|---|---|
| 1 | `(...)` | n/a |
| 2 | `**` | right to left |
| 3 | `+x`, `-x` (unary) | right to left |
| 4 | `*`, `/`, `//`, `%` | left to right |
| 5 | `+`, `-` (binary) | left to right |
Work through 1 + 2 * 3 ** 2:
3 ** 2is9.2 * 9is18.1 + 18is19.
Left associativity matters for non-commutative operators. 8 - 4 - 2 is (8 - 4) - 2, which is 2. 8 / 4 / 2 is (8 / 4) / 2, which is 1.0.
The operators *, /, //, and % share a level, so they run left to right. This catches people out in 10 // 3 * 3. It is (10 // 3) * 3, which is 9, not 10 // 9.
print(1 + 2 * 3 ** 2)
print(8 - 4 - 2)
print(8 / 4 / 2)
print(10 // 3 * 3)
print(-3 ** 2)
print(2 ** 3 ** 2)This prints 19, 2, 1.0, 9, -9, and 512.
Common errors
Forgetting parentheses in an average. a + b / 2 divides only b. The intended (a + b) / 2 needs the parentheses.
a, b = 10, 20
print(a + b / 2)
print((a + b) / 2)The output is 20.0 and 15.0.
Expecting / to return an int. Code that uses x / 2 as a list index fails with TypeError: list indices must be integers or slices, not float. Use // when you need a whole number.
Dividing by zero. /, //, and % all raise ZeroDivisionError when the right operand is zero, for ints and floats alike. Check the divisor first, or catch the exception where you can handle it meaningfully:
def safe_ratio(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(safe_ratio(1, 4))
print(safe_ratio(1, 0))This prints 0.25 and None. Note that 0 ** -1 also raises ZeroDivisionError, while 0 ** 0 is 1.
Assuming truncation. If you port code from C or Java, -7 // 2 gives -4 here, not -3. To truncate toward zero, use int(-7 / 2), which gives -3. This is fine for modest values, but it goes through a float, so it loses precision for ints larger than about 2**53. For exact results on large values, apply the floor division to the absolute values and restore the sign.
Mixing text and numbers. "Total: " + 5 raises TypeError: can only concatenate str (not "int") to str. Python does not convert between types in +. Strings do support + (concatenation) and * with an int (repetition), so "ab" * 3 is "ababab", but that is string behavior and not arithmetic. Converting between strings and numbers is covered in a later chapter.
Checking your predictions
A useful habit is to compute the answer by hand using the table, then run the code. If the two disagree, find which rule you misapplied. The identity a == (a // b) * b + a % b is a good test for any division expression you are unsure about.
for a, b in [(7, 2), (-7, 2), (7, -2), (-7, -2)]:
assert a == (a // b) * b + a % b
print(a, b, a // b, a % b)The loop prints four lines and the assert never fires. For (7, -2) you get -4 -1, and for (-7, -2) you get 3 -1.
Exercise
What do -7 // 2, -7 % 2, and -2 ** 2 evaluate to, and why does the result of -2 ** 2 differ from (-2) ** 2?
Show answer
-7 // 2 is -4, because floor division rounds down toward negative infinity (the exact quotient is -3.5). -7 % 2 is 1, because the identity a == (a // b) b + a % b requires -4 2 + 1 == -7. -2 ** 2 is -4, because ** binds tighter than the unary minus, so it is -(2 ** 2). (-2) ** 2 is 4, because the parentheses apply the exponent to -2.
Exercise
Write an expression using // and % that converts 3725 seconds into hours, minutes, and seconds, then state what it prints for print(h, m, s).
Show answer
One answer is h = 3725 // 3600, m = (3725 % 3600) // 60, s = 3725 % 60. It prints 1 2 5. An equivalent form is h, rest = divmod(3725, 3600) followed by m, s = divmod(rest, 60).