Menu
Coddy logo textTech

Modulo Operator

Part of the Fundamentals section of Coddy's Python journey — lesson 11 of 77.

The modulo operator % tells you what's left over after dividing one number by another.

result = dividend % divisor
  • dividend: The number being divided.
  • divisor: The number that divides the dividend.
  • result: The remainder of the division.

For example

result = 10 % 3

Here, 10 is divided by 3. 3 goes into 10 three times, with a remainder of 1. So, result will be 1.

Usually modulo is used for checking if a number is even or odd:

  • If a number is even, dividing it by 2 will leave a remainder of 0.
  • If a number is odd, dividing it by 2 will leave a remainder of 1.

To check this in code, we use the == operator, which checks if two values are equal to each other. For example, result == 0 asks "is result equal to 0?"

Special Case: When the dividend is smaller than the divisor, the result is simply the dividend itself.

For example:
5 % 8 = 5
Why? Since 8 cannot fit into 5 even once, the entire 5 remains as the remainder.

challenge icon

Challenge

Beginner

Write a code that initializes three variables, a, b and c with the values 9, 2, and 11 (respectively).

After that, initialize the following variables:

  • d that will hold the result of a modulo 2 
  • e that will hold the result of b modulo 3
  • f that will hold the result of c modulo 10

Check out the result and see how different dividends and divisors affect the result.

Cheat sheet

The modulo operator % returns the remainder of a division:

result = dividend % divisor

Example:

result = 10 % 3  # result is 1

Common use: checking if a number is even or odd

  • Even number: number % 2 == 0
  • Odd number: number % 2 == 1

Try it yourself

# Type your code below


# Don't change the line below
print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c}")
print(f"d = {d}")
print(f"e = {e}")
print(f"f = {f}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals