Modulo
The modulo operator (%
) in Python calculates the remainder of a division operation between two operands. When one number is divided by another, the modulo operation returns what remains after the division is performed.
The modulo operator is used in various programming scenarios including checking for even or odd numbers, implementing cyclic behavior, formatting data, and cryptographic applications. It’s a fundamental mathematical operation that helps solve problems where you need to work with remainders or create repeating patterns. In Python, the modulo operator works with different numeric types and offers uniquely consistent behavior with negative numbers compared to some other programming languages.
Syntax
a % b
Parameters:
a
: The dividend (the value being divided)b
: The divisor (the value dividing the dividend)
Return value:
The modulo operator returns the remainder of dividing a
by b
. The result will have the same sign as the divisor b
in Python.
Example 1: Modulo with Different Numeric Types
The following code demonstrates how the modulo operator works with integers, floats, and negative numbers:
# Modulo with integersprint(15 % 4)# Modulo with floatsprint(10.5 % 2.2)# Modulo with negative operandsprint(-7 % 3)print(7 % -3)
This code generates the following output:
31.69999999999999932-2
The output shows that modulo returns the remainder after division for each type of number. Python’s modulo operation with negative numbers always returns a result with the same sign as the divisor.
Example 2: Checking for Even and Odd Numbers
This example shows how to determine if a number is even or odd using the modulo operator:
def check_parity(number):if number % 2 == 0:return f"{number} is an even number"else:return f"{number} is an odd number"# Testing the function with various numbersprint(check_parity(4))print(check_parity(7))print(check_parity(0))print(check_parity(-5))
The output generated by the code above is:
4 is an even number7 is an odd number0 is an even number-5 is an odd number
The function works by checking if the remainder after dividing by 2 is zero(even) or not(odd). This technique is fundamental in programming for alternating actions, filtering data, or implementing algorithms that behave differently for even and odd values.
Codebyte Example: Creating a Time Converter
The code here uses modulo to convert total minutes into hours and minutes format:
The modulo operator finds the remaining minutes while integer division calculates the complete hours. This pattern of converting between units is common in applications dealing with time, distance, currency, and other measurements that use different scales.
Best Practices
Use for Checking Divisibility: The modulo operator is ideal for checking if a number is divisible by another.
# Check if number is divisible by 3if number % 3 == 0:print(f"{number} is divisible by 3")Use for Cycling Through Values: The modulo operator helps implement cyclic behavior.
# To cycle through array indicesnext_index = (current_index + 1) % array_lengthPrefer Integer Modulo: When possible, use modulo with integers for more predictable results.
Handle Negative Inputs Carefully: Be aware of how modulo treats negative numbers in Python, as it differs from some other programming languages.
Combine with Floor Division: When you need both the quotient and remainder, use floor division (
//
) and modulo together.quotient = a // bremainder = a % bUse
divmod()
for Combined Operations: Python provides a built-in functiondivmod()
that returns both the quotient and remainder as a tuple.quotient, remainder = divmod(a, b)
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours