Borislav Hadzhiev
Last updated: Jul 15, 2022
Photo from Unsplash
Use the modulo %
operator to check if a number is a multiple of 10, e.g.
if 100 % 10 == 0:
. The modulo %
operator returns the remainder from the
division of the first number by the second. If the remainder is 0
, the number
is a multiple of 10
.
if 100 % 10 == 0: print('number is multiple of 10') else: print('number is NOT multiple of 10') if 123 % 10 != 0: print('number is not multiple of 10')
We used the modulo %
operator to check if a number is a multiple of 10.
The modulo (%) operator returns the remainder from the division of the first value by the second.
print(100 % 10) # 👉️ 0 print(123 % 10) # 👉️ 3
If there is no remainder from the division, then the first number is an exact multiple of the second.
print(150 % 10) # 👉️ 0 print(150 % 10 == 0) # 👉️ True
10
is an exact multiple of 150
, so 150
is divisible by 10
with a
remainder of 0
.
If you need to check if a number is not divisible by 10
, use the modulo %
operator with the not equals !=
sign, e.g. if 123 % 10 != 0:
.
print(123 % 10) # 👉️ 3 if 123 % 10 != 0: print('number is not multiple of 10')
10
is not an exact multiple of 123
, so dividing 123
by 10
gives us a
remainder of 3
.
Here is an example that takes a number from user input and checks if it's a
multiple of 10
.
num = int(input('Enter a number: ')) print(num) # 👉️ 10 if num % 10 == 0: print('number is multiple of 10')
The input function
takes an optional prompt
argument and writes it to standard output without a
trailing newline.
Notice that we used the int()
class to convert the input string to an integer.
Even if the user enters a number, it still gets converted to a string.
If you need to check if a number is a multiple of two or more other numbers, use
the and
operator.
num = 30 if num % 10 == 0 and num % 15 == 0: print('30 is multiple of 10 and 15')
The expression x and y
returns the value to the left if it's falsy, otherwise
the value to the right is returned.
The if
block is only ran if both of the conditions evaluate to True
.
Conversely, if you need to check if a number is divisible by 1
of multiple
numbers, use the or
operator.
num = 30 if num % 13 == 0 or num % 10 == 0: print('30 is divisible by 13 or 10')
The expression x or y
returns the value to the left if it's truthy, otherwise
the value to the right is returned.
If either condition evaluates to True
, the if
block is ran.