Modulus
The modulus operation finds the remainder when one number is divided by another. It’s often shown using the percent symbol: %
Modulus code example
# Use modulus to find out how many people won't fit on the last bus
people = 53
bus_capacity = 20
left_behind = people % bus_capacity
print("People left behind:", left_behind)
number = 9
# Check if the number is even by seeing if the remainder when divided by 2 is 0
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
Modulus common uses
- Finding Remainders
- When dividing things into groups
- Example: 53 % 20 → 13 people don’t fit on a full bus of 20
- Checking Even or Odd Numbers
- If a number % 2 is 0, it’s even
- If it’s not 0, it’s odd
- Checking Multiples
- See if one number is a multiple of another
- Example: If number % 4 == 0 → multiple of 4!