← Python lessons

Modulo and Divisibility

The % operator — modulo — gives the remainder after a division. A remainder of 0 means the division was exact, which is how Python programs test whether one number divides another.

In this lesson, use positive integers for the number and divisor. The divisor must not be zero: dividing or taking a remainder with zero raises ZeroDivisionError.

Remainders

print(7 % 2)
print(8 % 2)
print(10 % 3)

7 % 2 is 1 because 2 goes into 7 three times with 1 left over. 8 % 2 is 0 because 2 divides 8 exactly.

Even or odd

n % 2 == 0 is the standard test for an even number:

for n in [4, 7, 10]:
    if n % 2 == 0:
        print(n, "is even")
    else:
        print(n, "is odd")

Checking one possible divisor

In number % divisor, the left value is the number being divided and the right value is the possible divisor.

number = 18
divisor = 6
if number % divisor == 0:
    print("Divides exactly")
else:
    print("Leaves a remainder")

This prints Divides exactly. Change divisor to 5 and the result is Leaves a remainder. The order matters: test whether the candidate divides the number, not whether the number divides the candidate.

See also: Data types and operations, The range() function, The accumulator pattern.

Your turn

Print the remainder when 23 is divided by 5. Then print whether 5 divides 23 exactly.

number = 23
divisor = 5
# Print the remainder, then print the Boolean comparison.

Expected output

3
False

Practise this in the free Python course, where every exercise checks your code instantly.