Division in Python uses three operators: / returns a float, // returns the quotient rounded down (floor division), and % returns the remainder. Dividing by zero with any of them raises ZeroDivisionError.
Lines starting with >>> below are example output from a Python prompt. They follow the behaviour described in the Python language reference.
The division operators at a glance
| Expression | Name | Example | Result |
|---|---|---|---|
a / b | True division | 7 / 2 | 3.5 |
a // b | Floor division | 7 // 2 | 3 |
a % b | Modulo (remainder) | 7 % 2 | 1 |
divmod(a, b) | Quotient and remainder | divmod(7, 2) | (3, 1) |
True division with /
The language reference says that division of integers yields a float. That holds even when the result is a whole number:
>>> 7 / 2
3.5
>>> 6 / 2
3.0
>>> 1 / 4
0.25
If you need an int from 6 / 2, you can either use // or wrap the result in int(). Which one you pick matters for negative numbers, covered below. The operands are first converted to a common type, so 7 / 2.0 and 7.0 / 2 both give 3.5.
A class can define its own behaviour for / through the special methods __truediv__() and __rtruediv__(). That is how libraries such as NumPy or fractions give / a meaning for their own types.
Floor division with //
Floor division returns the quotient with the floor function applied. For two int operands the result is an int. For two float operands the result is a float that holds a whole number, so the type is not always int:
>>> 7 // 2
3
>>> 7.0 // 2
3.0
>>> 17 // 5
3
A typical use is converting a count into larger units. For example, 200 minutes is 200 // 60 hours, which is 3, with 200 % 60 minutes left over, which is 20.
Floor division with negative numbers
This is where // surprises people. The Python docs state that the result is always rounded towards minus infinity. They give these cases: 1//2 is 0, (-1)//2 is -1, 1//(-2) is -1, and (-1)//(-2) is 0.
>>> -7 // 2
-4
>>> 7 // -2
-4
>>> -7 // -2
3
The exact quotient of -7 / 2 is -3.5. Rounding down gives -4, not -3. Many other languages truncate toward zero instead, so porting code that divides negative integers needs care.
If you want truncation toward zero, convert the true quotient with int(). The docs say that conversion from float to int truncates, discarding the fractional part:
>>> int(-7 / 2)
-3
>>> -7 // 2
-4
For very large integers, int(a / b) goes through a float and can lose precision, so prefer pure integer arithmetic when exactness matters. The same page points to math.floor() and math.ceil() for the other float-to-int conversions. To round a quotient up with integers only, a common idiom is -(-a // b).
The remainder with %
The % operator yields the remainder of dividing the first argument by the second. The reference says the result always has the same sign as its second operand (or is zero), and that its absolute value is strictly smaller than the absolute value of the second operand.
>>> 7 % 3
1
>>> -7 % 3
2
>>> 7 % -3
-2
Floating-point operands are allowed. The docs give 3.14 % 0.7 as equal to 0.34, since 3.14 equals 4*0.7 + 0.34. Because floats are approximate, a printed result may show tiny extra digits.
Floor division and modulo are linked by an identity from the reference: x == (x//y)*y + (x%y). That identity is why -7 // 2 must be -4 when -7 % 2 is 1: (-4)*2 + 1 is -7.
Checking even and odd numbers with n % 2 == 0 works for negative integers too, because the result is never negative when the divisor is positive.
Quotient and remainder together with divmod()
The built-in divmod(a, b) returns the pair of quotient and remainder. For integers the docs say the result is the same as (a // b, a % b):
>>> divmod(17, 5)
(3, 2)
>>> divmod(-7, 3)
(-3, 2)
>>> hours, minutes = divmod(200, 60)
>>> hours, minutes
(3, 20)
For floats, the docs say the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. So with floats, do not assume divmod matches math.floor(a / b) in every edge case.
//, % and divmod() are not defined for complex numbers.
Fix ZeroDivisionError
The exceptions reference describes ZeroDivisionError as raised when the second argument of a division or modulo operation is zero. That covers all three operators:
>>> 1 / 0
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
>>> 5 // 0
ZeroDivisionError: ...
>>> 5 % 0
ZeroDivisionError: ...
The message text differs between operators and Python versions (the ... stands for it), but the exception type is the same. The reliable fix is to decide what a zero divisor means in your program and handle it explicitly:
def average(total, count):
if count == 0:
return 0.0 # or raise a clearer error, or return None
return total / count
Alternatively, catch the exception with try and except ZeroDivisionError when the zero is rare and you cannot easily check ahead. See Python try and except for how to structure that. Catch only ZeroDivisionError, not a bare except, so that other bugs are not hidden.
Note that 0 / 5 is fine and gives 0.0. Only a zero on the right side raises.
Why division results look inexact
A float result from / is stored in binary. The Python tutorial explains that most decimal fractions cannot be represented exactly as binary fractions, and that the decimal value 0.1 cannot be represented exactly as a base 2 fraction. The stored value is the nearest representable binary fraction. This is why sums of divided values sometimes print extra digits:
>>> 1 / 3
0.3333333333333333
>>> 0.1 + 0.2
0.30000000000000004
When you need exact rational results, the fractions module represents numbers such as 1/3 exactly:
>>> from fractions import Fraction
>>> Fraction(1, 3) + Fraction(1, 6)
Fraction(1, 2)
For exact decimal arithmetic such as money, the tutorial points to the decimal module. To show a rounded result in output without changing the value, format it, for example with an f-string: f"{1 / 3:.2f}" gives '0.33'. See Python f-strings for the format options.
Python 2 and the old integer division
Older tutorials, written for Python 2, may say that 7 / 2 gives 3. In Python 3 the / operator is true division, and you write // for the old integer behaviour. If code you copied from an old tutorial gives different numbers, this is usually the reason.
Division, floor division and modulo in context
These three operators sit at the same precedence level as *, so they are evaluated left to right with multiplication. That means 10 / 2 * 5 is 25.0, not 1.0. The full precedence table and the other operator groups are in Python operators explained.
The augmented assignment forms /=, //= and %= divide a variable in place. Note that x /= 2 turns an int into a float, because the underlying operation is true division:
>>> x = 10
>>> x /= 2
>>> x
5.0
>>> x = 10
>>> x //= 2
>>> x
5
Which operator should you use?
- You want the exact quotient as a number: use
/. - You want a whole-number count, such as pages, rows per batch or hours: use
//. - You want what is left over, a wrap-around index or an even/odd test: use
%. - You want both whole units and the remainder: use
divmod(), which does the division once. - You want truncation toward zero for negative values: use
int(a / b), and remember the float limits for very large integers.
Frequently asked questions
- What is the difference between / and // in Python?
- The / operator is true division: dividing two integers gives a float, so 7 / 2 is 3.5 and 6 / 2 is 3.0. The // operator is floor division: the quotient is rounded toward minus infinity, so 7 // 2 is 3 and -7 // 2 is -4. Integer operands to // give an int.
- Why does -7 // 2 give -4 and not -3?
- Floor division always rounds toward minus infinity, not toward zero. The exact quotient -3.5 is rounded down to -4. If you want truncation toward zero, use int(-7 / 2), which gives -3, because converting a float to int discards the fractional part.
- How do I get both the quotient and the remainder in Python?
- Use divmod(a, b). For integers it returns (a // b, a % b). For example divmod(17, 5) returns (3, 2), meaning 17 is 3 times 5 plus 2.
- How do I avoid ZeroDivisionError?
- Check the divisor before dividing, or catch ZeroDivisionError with try and except. The error is raised by /, // and % (and divmod) when the second operand is zero, including 0 / 0 and 5 % 0.
- Does Python round the result of division?
- Only // rounds, and it rounds down. The / operator returns a float, which may itself be an approximation, because most decimal fractions cannot be stored exactly as binary floats. For exact results use the fractions module or the decimal module.
Sources
- Python Language Reference: Binary arithmetic operations (/, //, %)
- Python docs: Built-in Types (numeric operations and notes)
- Python docs: Built-in Functions (divmod)
- Python docs: Built-in Exceptions (ZeroDivisionError)
- Python Tutorial: Floating-Point Arithmetic: Issues and Limitations
- Python docs: fractions (Rational number arithmetic)