← Python lessons

Modulo and Divisibility

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

The % operator — modulo — gives the remainder after a division. A remainder of 0 means one number divides another exactly.

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.

Testing for an exact division

Compare the remainder with 0. The comparison gives True or False.

print(18 % 6 == 0)print(18 % 5 == 0)

This prints True, then False. 6 divides 18 exactly; 5 does not. The same test with 2 checks for an even number: 10 % 2 == 0 is True.

Checking one possible divisor

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

number = 18divisor = 6if 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.

🎯 Goal — make it print exactly:
3
False
number = 23divisor = 5# Print the remainder, then print the Boolean comparison.

Advanced reading

Practise this lesson

This exercise uses this lesson. It runs in your browser and checks your code instantly — no sign-up needed.

Python Fundamentals