Understanding the modulo operator in Python

The modulo operator is a simple tool. It finds the remainder after division. In Python, we write it as %.

What is the modulo operator?

Think of it like this: when you divide two numbers, you often get a leftover. The modulo gives you that leftover. For example, 7 % 3 equals 1. That 1 is the remainder.

How it works — quick examples

5 % 2 equals 1, because 5 divided by 2 is 2 with 1 left over. 10 % 5 equals 0, because 10 divides evenly by 5.

Use it to test even or odd numbers. If n % 2 == 0, then n is even. If n % 2 == 1, then n is odd.

It also helps when you need to loop around a list. Say you have 3 items and you use an index i % 3. The index will always land on 0, 1, or 2. So this means you can cycle through items without errors.

Common real-world uses

Check if a number is divisible by another. Do math with clock times, like hours or minutes. Wrap array or list indices so they stay inside bounds. Create repeating patterns in games or visuals.

Watch out for negative numbers

Modulo with negatives can surprise you. In Python, the result matches the sign of the divisor. For example, -7 % 3 equals 2. That might feel odd at first. Just remember: Python chooses a remainder so the result stays non-negative when the divisor is positive.

Small challenges to try

1) What is 14 % 4? (Answer: 2.)

2) How would you use % to check if a year is divisible by 4? (Hint: year % 4.)

3) Use i % n to cycle through a list of n items in a loop.

Quick tips

Use % for remainders. Use it to check divisibility. Use it to wrap indexes. And be careful with negatives.

Wrap up

Modulo is small but useful. It helps with remainders, cycles, and simple checks. Try a few examples in Python and you’ll get a feel for it fast.

Scroll to Top