Arithmetic operators · 3 / 18 Theory

Division in Python: /, // and %

Python has three division-related operators, and each one answers a different question: what is the result?, how many times does it fit? and what is left over?

Normal division: /

It always returns a decimal number (float), even when the division is exact:

print(7 / 2)   # 3.5
print(8 / 2)   # 4.0

Floor division: //

It returns how many times the divisor fits in the dividend, with no decimals:

print(7 // 2)    # 3
print(7.5 // 2)  # 3.0  (with decimals the result is still a float)

With negative numbers it rounds down, not towards zero. This is a common surprise:

print(-7 // 2)   # -4

Modulo (remainder): %

It returns what is left over after dividing:

print(7 % 2)     # 1  (7 = 3 * 2 + 1)
print(7.5 % 2)   # 1.5

The three operators are related: it is always true that a == (a // b) * b + a % b.

divmod(): quotient and remainder at once

print(divmod(7, 2))   # (3, 1)

seconds = 3725
minutes, rest = divmod(seconds, 60)
print(minutes, rest)   # 62 5

What the modulo is for

  • Checking whether a number is even: n % 2 == 0.
  • Checking whether a number is a multiple of another: n % 5 == 0.
  • Getting the last digit of a number: 17 % 10 is 7.
  • Removing the last digit: 17 // 10 is 1.
  • Converting units: from seconds to minutes and seconds, from cents to euros and cents.

Practice in the exercise about division and the remainder of a division.