What does // mean in Python?
Short answer: // is the floor division operator. It divides two numbers and rounds the result down to the nearest whole number: 19 // 5 returns 3, while 19 / 5 returns 3.8. "Down" means toward negative infinity, so -19 // 5 returns -4, not -3. With two integers the result is an int; if either number is a float, the result is a float, such as 10 // 2.5, which returns 4.0.
// is the partner of %: // gives you how many whole times one number fits into another, and % gives you what is left over. Python guarantees that (a // b) * b + a % b == a for any numbers.
/ keeps the decimals. // moves to the whole number on the left of the result on the number line, also with negative numbers.
Floor division at a glance
| Expression | Result | Why |
|---|---|---|
19 / 5 | 3.8 | Regular division always returns a float |
19 // 5 | 3 | 3.8 rounded down |
19 % 5 | 4 | The remainder: 3 × 5 + 4 = 19 |
-19 // 5 | -4 | -3.8 rounded down is -4 |
-19 % 5 | 1 | -4 × 5 + 1 = -19 |
10 // 2.5 | 4.0 | A float in the operation gives a float |
divmod(19, 5) | (3, 4) | // and % in one call |
x //= 5 | x becomes x // 5 | Augmented assignment |
7 // 0 | ZeroDivisionError | You cannot divide by zero |
// vs / in Python
In Python 3, / is true division: it always returns a float, even when the division is exact. // throws the decimals away by rounding down.
print(19 / 5) # 3.8
print(19 // 5) # 3
print(20 / 5) # 4.0 (a float, even if it is exact)
print(20 // 5) # 4 (an int)If you are reading old Python 2 code, be careful: there, / between two integers already did floor division. Python 3 separated the two operations, so // is the one to use whenever you want a whole number.
Floor division with negative numbers
This is the part that surprises people. Rounding "down" means moving toward negative infinity, not toward zero:
print(19 // 5) # 3 (3.8 rounded down)
print(-19 // 5) # -4 (-3.8 rounded down)
print(19 // -5) # -4
print(-19 // -5) # 3If you want to cut the decimals toward zero instead, use int() or math.trunc():
import math
print(int(-19 / 5)) # -3
print(math.trunc(-19 / 5)) # -3
print(math.floor(-19 / 5)) # -4, the same as -19 // 5Floor division with floats
When either number is a float, // still rounds down, but the result is a float:
print(10 // 2.5) # 4.0
print(17.5 // 3.3) # 5.0
print(7.5 // 2) # 3.0
print(-7.5 // 2) # -4.0Wrap it in int() when you need an integer type, for example to use the result as a list index: int(17.5 // 3.3) returns 5.
// and % together: divmod()
divmod(a, b) returns both results as a tuple, which is handy for unit conversions:
total_seconds = 125
minutes, seconds = divmod(total_seconds, 60)
print(minutes, seconds) # 2 5With negative numbers, % takes the sign of the divisor, so -19 % 5 is 1 and divmod(-19, 5) is (-4, 1). That is what keeps (a // b) * b + a % b == a true.
