Python Modulo: Using the % Operator (Overview)

Python supports a wide range of arithmetic operators that you can use when working with numbers in your code. One of these operators is the modulo operator (%), which returns the remainder of dividing two numbers. Modular operations are useful to check if a number is even or odd, simplifying cycling through data, and doing non-decimal based units conversion.

In this course, you’ll learn:

  • How modulo works in mathematics
  • How to use the Python modulo operator with different numeric types
  • How Python calculates the results of a modulo operation
  • How to override .__mod__() in your classes to use them with the modulo operator
  • How to use the Python modulo operator to solve real-world problems

The code in this course was tested with Python 3.9.0, % has not change much and older versions should be compatible.


Sample Code (.zip)

2.4 KB

Course Slides (.pdf)

696.4 KB

00:00 Welcome to Python Modulo in Practice, or How to Use the % Operator. My name is Chris and I will be your guide. In this course, you’ll learn about modular arithmetic, how to use the percent operator (%) with int and float types, common coding uses of the % operator, and how to use % with custom classes.

00:22 Python’s % operator’s been around for a long time. The code I’m going to show you has all been tested using Python 3.9, but you should be able to use it in pretty much any version of Python.

00:34 So, what’s it for? Well, the % operator does modular arithmetic. That means getting the remainder portion of doing some division. For example, 14 divided by 4 is 3 remainder 2.

00:48 3 times 12 is 12, and there’s 2 leftover. 14 mod 4 returns 2, the remainder from the division. Python’s operator for that mod operation is percent (%). Modulus pops up in a bunch of places inside of your code.

01:03 Some common uses are detecting even versus odd numbers, looping on cycles of data, doing unit conversion—for example, if you want to take a large number of inches and turn it into feet and inches if you’re using the American Imperial system.

01:19 Or, if you want to take a large number of minutes and turn it into hours and minutes, you’ll need the modulus operation.

01:26 Everything in Python is an object, so you can take advantage of this and write your own objects that support the % operator. You do this by overriding .__mod__().

01:36 I’ll show you how to do this later on in the course.

01:39 Next up, an introduction to modular arithmetic.

Become a Member to join the conversation.