% in Python

E-mc2 written on chalkboard


% in Python is the modulo operator. It calculates the remainder of a division between two integers.

For example, dividing 10 to 3 evenly is impossible. There will be one leftover. To verify this using Python, write:

leftovers = 10 % 3
print(leftovers)

Output:

1

A real-life example of using modulo in Python: How many slices of pizza are leftover when 5 pieces are shared evenly in a group of 3?

Answer:

print(5 % 3)

Output:

2

Modulo and Divisibility in Python

If a % b (a modulo b) returns 0, it’s said a is evenly divisible by b. In other words, sharing a to b gives no leftovers.

In the pizza slice context, this means the slices are shared evenly. In other words, there are no leftover slices.

For example, sharing 12 slices of pizza evenly for a group of 6 means no slices are leftover. This can be verified using the modulo operation:

print(12 % 6)

Output:

0

Modulo Example: How to Check If a Year is a Leap Year

Definition. A leap year is a year that is evenly divisible by 4 or 400. The exception is that years divisible by 100 are not leap years (unless they are divisible by 400). For example, 2016, 2000, 1600 are leap years but 2011 and 1900 are not.

Task. Write a program that checks if a given year is a leap year.

Answer. To solve this problem, you need to figure out if a given year is divisible by 4 but not by 100 unless it’s divisible by 400.

To turn this into code, you get this kind of result:

def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

Example usage:

print(is_leap(2000))  # --> True
print(is_leap(1900))  # --> False
print(is_leap(2016))  # --> True

If this answer rings no bells, here is a complete guide on how to figure out leap years in Python.

Conclusion

% in Python is used to calculate the remainder of a division.

For example 5 % 3 returns 2. In other words, sharing 5 units evenly with 3 is not possible. There will be 2 leftover units.

A good task to test your modulo skills is to write a program for checking if a year is a leap year.

def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

Thanks for reading. Happy coding!

Further Reading

How to Find a Leap Year in Python Using Modulo %

10 Useful Python Tips and Tricks

Resources

https://docs.python.org/3/

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published.