How do I use the % operator?


#1

Question

How do I use the % operator?

Answer

The modulo operator, %, returns the result after division.
You divide the left by the right, as normal, and the result is the remainder, like this:

my_modulo_result = 100 % 10
print my_modulo_result  # prints 0

In the example above, 100 is evenly divisible by 10, so there is no remainder, and our result is 0.
If we wanted to check if a number is divisible by 3, we could do:
if number % 3 == 0: and if it’s True, then it must be evenly divisible by 3. We can do the same for any number!


FAQ: Learn Python - Practice Makes Perfect - is_even