How to Check if a Number is Divisible by Another Number in Python
Determining if one number can be evenly divided by another is a fundamental arithmetic operation used in various programming tasks, from data validation to mathematical algorithms like finding factors or checking for even/odd numbers.
Python provides a straightforward way to perform this check using the modulo operator.
This guide demonstrates how to check for divisibility in Python, handle multiple conditions, and filter lists based on divisibility.
The Modulo Operator (%
) for Divisibility
The core tool for checking divisibility in Python is the modulo operator (%
). This operator performs division but returns only the remainder of that division.
remainder1 = 10 % 3 # 10 divided by 3 is 3 with a remainder of 1
print(remainder1) # Output: 1
remainder2 = 12 % 4 # 12 divided by 4 is 3 with a remainder of 0
print(remainder2) # Output: 0
remainder3 = 15 % 4 # 15 divided by 4 is 3 with a remainder of 3
print(remainder3) # Output: 3
The key insight for divisibility is: If a number A
is perfectly divisible by another number B
, the remainder of their division (A % B
) will be exactly 0.
Checking if a Number IS Divisible by Another
To check if number_a
is divisible by number_b
, calculate number_a % number_b
and see if the result is equal (==
) to 0.
number_a = 16
number_b = 4
is_divisible = (number_a % number_b == 0)
print(f"Remainder of {number_a} % {number_b} is: {number_a % number_b}")
# Output: Remainder of 16 % 4 is: 0
print(f"Is {number_a} divisible by {number_b}? {is_divisible}")
# Output: Is 16 divisible by 4? True
if number_a % number_b == 0:
print(f"{number_a} is perfectly divisible by {number_b}.")
else:
print(f"{number_a} is NOT perfectly divisible by {number_b}.")
Output:
Remainder of 16 % 4 is: 0
Is 16 divisible by 4? True
16 is perfectly divisible by 4.
Checking if a Number is NOT Divisible by Another
To check if number_a
is not divisible by number_b
, calculate number_a % number_b
and see if the result is not equal (!=
) to 0.
number_a = 17
number_b = 4
is_not_divisible = (number_a % number_b != 0)
print(f"Remainder of {number_a} % {number_b} is: {number_a % number_b}")
# Output: Remainder of 17 % 4 is: 1
print(f"Is {number_a} NOT divisible by {number_b}? {is_not_divisible}")
# Output: Is 17 NOT divisible by 4? True
if number_a % number_b != 0:
print(f"{number_a} is NOT perfectly divisible by {number_b}.")
else:
print(f"{number_a} is perfectly divisible by {number_b}.")
Output:
Remainder of 17 % 4 is: 1
Is 17 NOT divisible by 4? True
17 is NOT perfectly divisible by 4.
Filtering Lists for Divisible Numbers
You can easily extract numbers from a list that are divisible by a specific divisor.
Using List Comprehension
List comprehensions provide a concise way to create a new list based on an existing one, filtering elements based on a condition.
numbers = [10, 15, 20, 25, 30, 35, 40]
divisor = 5
# Create a new list containing only numbers divisible by 'divisor'
divisible_by_5 = [num for num in numbers if num % divisor == 0]
print(f"Original list: {numbers}")
# Output: Original list: [10, 15, 20, 25, 30, 35, 40]
print(f"Numbers divisible by {divisor}: {divisible_by_5}")
# Output: Numbers divisible by 5: [10, 15, 20, 25, 30, 35, 40]
# Example: Divisible by 10
divisible_by_10 = [num for num in numbers if num % 10 == 0]
print(f"Numbers divisible by 10: {divisible_by_10}")
# Output: Numbers divisible by 10: [10, 20, 30, 40]
Output:
Original list: [10, 15, 20, 25, 30, 35, 40]
Numbers divisible by 5: [10, 15, 20, 25, 30, 35, 40]
Numbers divisible by 10: [10, 20, 30, 40]
The expression num % divisor == 0
acts as the filter condition within the list comprehension.
Using the filter()
Function
The built-in filter()
function can achieve the same result, often used with a lambda
function for the condition.
numbers = [10, 15, 20, 25, 30, 35, 40]
divisor = 10
# Use filter with a lambda function to check divisibility
filtered_iterator = filter(lambda x: x % divisor == 0, numbers)
# Convert the filter object (iterator) to a list
divisible_by_10_filter = list(filtered_iterator)
print(f"Original list: {numbers}")
print(f"Numbers divisible by {divisor} (using filter): {divisible_by_10_filter}")
# Output: Numbers divisible by 10 (using filter): [10, 20, 30, 40]
lambda x: x % divisor == 0
: An anonymous function that takes an elementx
and returnsTrue
if it's divisible bydivisor
,False
otherwise.filter(...)
: Returns an iterator yielding only the elements for which the lambda function returnedTrue
.list(...)
: Converts the iterator into a list.
Handling User Input for Divisibility Checks*
When getting numbers from user input, remember that the input()
function returns a string. You must convert these strings to integers using int()
before performing arithmetic operations like modulo.
try:
input_str_1 = input('Enter the dividend (number to be divided): ')
num_1 = int(input_str_1)
input_str_2 = input('Enter the divisor: ')
num_2 = int(input_str_2)
if num_2 == 0:
print("Error: Can not divide by zero.")
elif num_1 % num_2 == 0:
# Example: User enters 20 and 5
print(f"{num_1} IS divisible by {num_2}")
else:
# Example: User enters 20 and 6
print(f"{num_1} is NOT divisible by {num_2}")
except ValueError:
print("Invalid input. Please enter whole numbers only.")
except ZeroDivisionError: # Though checked explicitly above, good practice
print("Error: Division by zero is not allowed.")
Always include error handling (like try...except
for ValueError
if the input isn't a valid integer, and checking for division by zero) when dealing with user input.
Checking Divisibility by Multiple Numbers (AND Condition)
To check if a number is divisible by two or more other numbers, use the logical and
operator to combine multiple modulo checks. The overall condition is True
only if all individual divisibility checks are True
.
num = 30
# Check if num is divisible by 2 AND 3 AND 5
if num % 2 == 0 and num % 3 == 0 and num % 5 == 0:
# This block runs for num = 30
print(f"{num} is divisible by 2, 3, and 5.")
else:
print(f"{num} is NOT divisible by all of 2, 3, and 5.")
num = 20
if num % 2 == 0 and num % 3 == 0 and num % 5 == 0:
print(f"{num} is divisible by 2, 3, and 5.")
else:
# This block runs for num = 20 (because 20 % 3 != 0)
print(f"{num} is NOT divisible by all of 2, 3, and 5.")
Checking Divisibility by One of Multiple Numbers (OR Condition)
To check if a number is divisible by at least one of several other numbers, use the logical or
operator. The overall condition is True
if any of the individual divisibility checks are True
.
num = 21
# Check if num is divisible by 5 OR 7
if num % 5 == 0 or num % 7 == 0:
# This block runs for num = 21 (because 21 % 7 == 0)
print(f"{num} is divisible by 5 or 7 (or both).")
else:
print(f"{num} is divisible by neither 5 nor 7.")
num = 12
if num % 5 == 0 or num % 7 == 0:
print(f"{num} is divisible by 5 or 7 (or both).")
else:
# This block runs for num = 12
print(f"{num} is divisible by neither 5 nor 7.")
Conclusion
Checking for divisibility in Python is efficiently handled using the modulo operator (%
).
- A remainder of
0
indicates that a number is perfectly divisible by another. - You can combine this check with standard comparison operators (
==
,!=
) and logical operators (and
,or
) to test various conditions. - List comprehensions and the
filter()
function offer concise ways to select numbers from a list based on divisibility criteria.
Remember to convert user input to integers using int()
and handle potential errors like non-numeric input or division by zero.