What is Modulo Operator in Python: Explanation and Examples
modulo operator (%) in Python returns the remainder after dividing one number by another. It is used to find what is left over when one number is divided by another.How It Works
Think of the modulo operator like sharing candies among friends. If you have 10 candies and 3 friends, you can give each friend 3 candies, but 1 candy will be left undistributed. That leftover candy is what the modulo operator gives you.
In Python, when you write a % b, it divides a by b and returns the remainder. For example, 10 % 3 equals 1 because 3 goes into 10 three times (3x3=9) and leaves 1.
This operator works with integers and floats, but it is most commonly used with whole numbers to find remainders.
Example
This example shows how to use the modulo operator to find the remainder of division.
a = 17 b = 5 remainder = a % b print(f"The remainder when {a} is divided by {b} is {remainder}")
When to Use
The modulo operator is useful when you need to check if a number is divisible by another, or when you want to cycle through a set of values repeatedly.
For example, you can use it to find out if a number is even or odd by checking number % 2. If the result is 0, the number is even; if 1, it is odd.
It is also helpful in programming tasks like wrapping around indexes in a list, scheduling repeated events, or working with clock times.
Key Points
- The modulo operator
%returns the remainder of division. - It helps determine divisibility and cycle through values.
- Commonly used to check even/odd numbers and wrap-around logic.
- Works with integers and floats but mostly used with integers.