Skip to main content

How to Check If a Number Is Divisible by Another in Python

Checking for divisibility is a fundamental operation in programming, used in tasks ranging from determining even/odd numbers to distributing items evenly in a UI grid. In Python, this is achieved using the modulo operator %, which returns the remainder of a division.

This guide explains how to use the modulo operator, handle common edge cases like division by zero, and apply this logic in real-world scenarios.

Understanding the Modulo Operator %

The modulo operator calculates the remainder of dividing the left operand by the right operand.

  • 10 % 3 returns 1 (because 10 = 3 × 3 + 1).
  • 10 % 5 returns 0 (because 10 = 5 × 2 + 0).

Key Rule: If a % b == 0, then a is perfectly divisible by b.

Method 1: Basic Divisibility Check

To check divisibility, compare the modulo result to zero.

number = 10
divisor = 2

# ✅ Correct: Check remainder
if number % divisor == 0:
print(f"{number} is divisible by {divisor}")
else:
print(f"{number} is NOT divisible by {divisor}")

Output:

10 is divisible by 2

Method 2: Handling Division by Zero

Division by zero is mathematically undefined and raises a ZeroDivisionError in Python. Before performing a modulo operation, you must ensure the divisor is not zero.

Using try-except (Robust)

def check_divisibility(a, b):
try:
if a % b == 0:
return True
else:
return False
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
return False

print(f"10 divisible by 0? {check_divisibility(10, 0)}")

Output:

Error: Cannot divide by zero.
10 divisible by 0? False

Using if Check (Explicit)

a = 10
b = 0

if b != 0 and a % b == 0:
print("Divisible")
elif b == 0:
print("Error: Divisor cannot be zero")
else:
print("Not Divisible")

Output:

Error: Divisor cannot be zero

Practical Examples (Even/Odd, FizzBuzz)

Even or Odd?

An even number is always divisible by 2.

num = 7

if num % 2 == 0:
print("Even")
else:
print("Odd")

Output:

Odd

Cycling Through Colors

The modulo operator is excellent for cycling through a fixed list of items repeatedly.

colors = ["Red", "Green", "Blue"]
items = range(5) # 0, 1, 2, 3, 4

for i in items:
# 0%3=0, 1%3=1, 2%3=2, 3%3=0, 4%3=1
color = colors[i % len(colors)]
print(f"Item {i} gets color: {color}")

Output:

Item 0 gets color: Red
Item 1 gets color: Green
Item 2 gets color: Blue
Item 3 gets color: Red
Item 4 gets color: Green

Conclusion

To check divisibility in Python:

  1. Use a % b == 0 as the standard check.
  2. Validate b != 0 to prevent runtime crashes.
  3. Use Modulo for cycling patterns or checking constraints (like "every nth item").