View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Modulus in Python

Updated on 23/01/20257,351 Views

Modulus in Python is a mathematical operation that returns the remainder of a division. While division provides the quotient, the modulus operator focuses on the remainder.

But what’s the difference between division and modulus in Python? Many new Python users often confuse the two. Understanding this distinction is crucial for effective coding.

In this guide, you’ll get a clear modulus in Python with example to see how it works in real scenarios.  

By the end of this tutorial, you’ll gain a deeper understanding of the modulus operation and its difference from division. Keep Reading!

“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”

Understanding the Modulus Operator in Python

The modulus operator in Python is represented by the percent sign (%). It calculates the remainder of the division between two numbers. Unlike normal division, which gives the quotient (the result of the division), the modulus operator gives you the leftover value. 

To clarify, let’s start with an example. 

Suppose we have the numbers 17 and 5, and we want to know what the remainder is when we divide 17 by 5: 

# Using the modulus operator
remainder = 17 % 5
print(remainder)

Output: 

2

In this case, 17 divided by 5 gives a quotient of 3 (because 5 goes into 17 three times), but the remainder is 2. That’s what the modulus operator gives you—the remainder of the division.

Difference Between Division and Modulus in Python

Now, let's look at the difference between division and modulus in Python. The division operator (/) gives you the quotient, while the modulus operator (%) gives you the remainder.

Let’s break it down with an example: 

# Division operation
quotient = 17 / 5
print("Quotient:", quotient)
# Modulus operation
remainder = 17 % 5
print("Remainder:", remainder)

Output: 

Quotient: 3.4Remainder: 2

Here, 17 divided by 5 gives a quotient of 3.4 (because Python performs floating-point division). But when you use the modulus operator, you get the remainder, which is 2. 

This is the key difference: division gives the result of dividing two numbers, while modulus gives the leftover part after the division.

Understanding the Modulus with Example

Let’s dive deeper with an example using both division and modulus for integers. Consider the division of 22 by 7: 

# Using division and modulus together
quotient = 22 // 7  # This gives us the quotient without any remainder (integer division)
remainder = 22 % 7   # This gives us the remainder after the division
print("Quotient:", quotient)
print("Remainder:", remainder)

Output: 

Quotient: 3Remainder: 1

In this example:

  • The division gives the quotient as 3 (7 goes into 22 three times).
  • The modulus operator gives the remainder as 1 (the leftover part after the division).

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

Basic Usage of Modulus Operator

In this section, we'll explore how to use the modulus operator (%) in Python with different types of numbers. We'll start with integers, move to floating-point numbers, and then examine how Python handles negative numbers.

Modulo Operator with Integer

Let's start with the basic usage of the modulus operator on integers. When you apply the modulus operator to two integers, Python returns the remainder of the division.

For example, let’s calculate the modulus of 17 and 5: 

# Modulo with integers
result = 17 % 5
print("17 % 5 =", result)

Output: 

17 % 5 = 2

Explanation:

  • The division of 17 by 5 gives a quotient of 3 and a remainder of 2 (because 5 fits into 17 three times, with 2 left over).
  • The modulus operator returns this remainder (2), not the quotient.
  • This example demonstrates modulus in Python with example, showing how it works with integers.

Modulo Operator with Float

Now, let's look at the modulus operator with float numbers. Modulus also works with floating-point numbers in Python, but the result will be a floating-point remainder.

Consider the following example: 

# Modulo with floats
result_float = 7.5 % 2.5
print("7.5 % 2.5 =", result_float)

Output: 

7.5 % 2.5 = 0.0

Explanation:

  • When you divide 7.5 by 2.5, the quotient is 3, with no remainder. Thus, the result of the modulus operation is 0.0.
  • This shows that the modulus operator works with floats as well, and it can be useful when dealing with decimal values.
  • Notice how the result is a floating-point number (0.0), even though the remainder is essentially zero.

Modulo Operator with a Negative Number

Python’s modulus operator handles negative numbers a bit differently. The result of the modulus operation always has the same sign as the divisor (the second number). This is an important distinction between division and modulus in Python.

Let’s see how Python handles a negative number in the modulus operation:

# Modulo with a negative number
result_negative = -17 % 5
print("-17 % 5 =", result_negative)

Output: 

-17 % 5 = 3

Explanation:

  • When we divide -17 by 5, we get a quotient of -4 and a remainder of 3. The remainder must always have the same sign as the divisor (in this case, 5), so Python adjusts the remainder to be positive, even though the dividend was negative.
  • This behavior can be confusing at first, but it's consistent across Python and follows the rule that the remainder has the same sign as the divisor.

These examples give you a solid understanding of how the modulus operator works in Python across different data types

Modulus in Python with Loops and Functions

Let’s explore how we can apply it in more practical scenarios, like using it inside loops, with functions, and even working with libraries like numpy.  

Get the Modulus of Two Integers Using a While Loop

One practical way to use the modulus operator is inside loops. For example, let’s use a while loop to calculate the modulus of two integers. This approach can be helpful when you need to calculate remainders in a series of divisions repeatedly.

Here’s how you can do it: 

# Calculate modulus using a while loop
numerator = 23
denominator = 4
while numerator >= denominator:
    numerator -= denominator  # Subtract the denominator repeatedly
print("The remainder is:", numerator)

Output: 

The remainder is: 3

Explanation:

  • In this example, we subtract 4 from 23 repeatedly until 23 becomes less than 4. The remaining value (3) is the modulus, as 23 % 4 = 3.
  • This shows how you can calculate the modulus using basic subtraction inside a loop, without using the modulus operator directly. The modulus in Python with example shows a more manual way to get the remainder.

Get the Modulus of N Numbers Using a Function

Sometimes, you might want to compute the modulus of a set of numbers using a function. This is especially useful when you have a list of numbers and need to calculate the remainder for multiple divisions.

Here’s a function that takes multiple numbers and returns the modulus of them: 

# Function to calculate modulus of n numbers
def modulus_of_numbers(*numbers):
    result = numbers[0]  # Start with the first number
    for num in numbers[1:]:  # Loop through the rest of the numbers
        result = result % num  # Calculate modulus with each number
    return result
# Using the function to calculate modulus
print("Modulus of numbers:", modulus_of_numbers(100, 7, 3))

Output: 

Modulus of numbers: 2

Explanation:

  • The function modulus_of_numbers takes any number of arguments and calculates the modulus sequentially. First, it calculates 100 % 7, which results in 2, and then it calculates 2 % 3, which gives 2.
  • This function is useful when you need to find the modulus of multiple numbers in a series of divisions.

Also Read: Difference Between Function and Method in Python

Get the Modulus of a Given Array Using the divmod() Function

Python also provides a built-in function called divmod() that returns both the quotient and the remainder as a tuple. This can be very useful when you need both results at once.

Let’s see an example: 

# Using divmod to get both quotient and remainder
quotient, remainder = divmod(17, 5)
print("Quotient:", quotient)
print("Remainder:", remainder)

Output: 

Quotient: 3Remainder: 2

Explanation:

  • The divmod(17, 5) function returns a tuple. The first element is the quotient (3), and the second element is the remainder (2).
  • This is very useful when you need both the quotient and the remainder in a single operation, instead of doing two separate calculations.
  • Using divmod() helps simplify your code when you need both values, and it can be applied with both integers and floating-point numbers.

Get the Modulus of Two Numbers Using Numpy

If you’re working with arrays of numbers and need to calculate the modulus, numpy offers a powerful tool. The numpy.mod() function calculates the modulus element-wise for arrays, making it very efficient.

Let’s look at how to use it: 

import numpy as np
# Using numpy to calculate modulus
array1 = np.array([10, 20, 30])
array2 = np.array([3, 5, 7])
result = np.mod(array1, array2)
print("Modulus of arrays:", result)

Output: 

Modulus of arrays: [1 0 2]

Explanation:

  • The numpy.mod() function takes two arrays, array1 and array2, and calculates the modulus element-wise. For example:
    • 10 % 3 = 1
    • 20 % 5 = 0
    • 30 % 7 = 2
  • This is extremely useful for operations on large datasets where you need to apply the modulus operation to each element in an array.

Also Read: Libraries in Python Explained: List of Important Libraries

Get the Modulus of Two Numbers Using the fmod() Function

Python’s math module provides a function called fmod() that is used to compute the modulus of two floating-point numbers. 

While the % operator works fine for most cases, fmod() offers a bit more precision, especially when dealing with very small floating-point numbers.

Here’s how you can use math.fmod(): 

import math
# Using fmod() to get the modulus of two float numbers
result_fmod = math.fmod(12.5, 4.2)
print("math.fmod(12.5, 4.2) =", result_fmod)

Output: 

math.fmod(12.5, 4.2) = 4.1

Explanation:

  • The math.fmod(12.5, 4.2) function returns the remainder when 12.5 is divided by 4.2. The result is 4.1, which is the remainder.
  • The key difference here is that fmod() gives a more precise result for floating-point operations compared to the % operator, particularly for numbers that are very close to zero or have a large number of decimal places.

We’ve covered several practical ways to use the modulus in Python with example. 

Handling Modulus Exceptions

One of the most common errors is trying to use the modulus operator with a divisor of zero, which can lead to a ZeroDivisionError. Let’s explore how to handle modulus exceptions effectively in Python.

ZeroDivisionError in Python

A ZeroDivisionError occurs when you attempt to divide or take the modulus with zero. This is a serious issue because division by zero is undefined in mathematics. In Python, attempting to calculate the modulus with zero as the divisor will raise this error.

Let’s see an example: 

# Modulus with zero divisor
try:
    result = 10 % 0  # Trying to divide by zero
except ZeroDivisionError as e:
    print("Error:", e)

Output: 

Error: integer division or modulo by zero

Explanation:

  • Here, we try to calculate 10 % 0, which raises a ZeroDivisionError because modulus by zero is mathematically undefined.
  • To handle this, we use a try-except block. If the error occurs, Python jumps to the except block and prints the error message: "integer division or modulo by zero".
  • This is a good practice to ensure your program doesn't crash when unexpected errors like this arise. You should always anticipate such edge cases, especially when performing division or modulus operations.

Exceptions in Python Modulus Operator

While the ZeroDivisionError is the most common exception related to the modulus operator, there are other potential issues you might face, especially when working with different data types. 

Let’s explore some other exceptions you should be aware of and how to handle them.

  1. TypeError:
    • If you attempt to apply the modulus operator to incompatible types (e.g., a string and an integer), Python will raise a TypeError.

Example:

try:
    result = "hello" % 3  # Trying to take modulus of a string
except TypeError as e:
    print("Error:", e)

Output: 

Error: not all arguments converted during string formatting

Explanation:

  • In this case, we're trying to apply the modulus operator between a string ("hello") and an integer (3), which isn't valid. Python raises a TypeError because the modulus operator can only be used between numbers (either integers or floats).
  • Again, we use a try-except block to catch this error and print a relevant message. This ensures that your program continues running even if an invalid operation is attempted.
  1. ValueError:
    • A ValueError might occur in some specific cases where you expect a numerical value but receive something else (e.g., passing a string that cannot be converted into a number).

Example:

try:
    result = int("hello") % 3  # Trying to convert a non-numeric string to an integer
except ValueError as e:
    print("Error:", e)

Output:

Error: invalid literal for int() with base 10: 'hello'

Explanation:

  • Here, we are trying to convert the string "hello" into an integer using int("hello"). Since "hello" is not a valid number, Python raises a ValueError.
  • This error is caught, and we print the message to inform the user of the issue.

Best Practices for Handling Modulus Exceptions

To ensure smooth handling of modulus operations and prevent your program from crashing due to exceptions, follow these best practices:

  1. Validate inputs: Always validate that the divisor is not zero before performing modulus operations.
  2. Use try-except blocks: As shown in the examples, use try-except blocks to catch and handle exceptions.
  3. Check types: Ensure that the operands are of compatible types (either integers or floats).
  4. Provide meaningful error messages: When catching exceptions, provide clear and helpful error messages to guide the user on what went wrong.

By using proper exception-handling techniques, you can ensure that your program behaves predictably even when faced with unexpected input or errors, making your code more reliable and user-friendly.

FAQs

1. What is the modulus operator in Python?

The modulus operator in Python (%) returns the remainder when one number is divided by another. It helps in finding the leftover value after division, also known as the remainder.

2. How does modulus work in Python with example?

For example, 29 % 6 will return 5, as 6 divides into 29 four times with a remainder of 5. This is another illustration of modulus in Python with example.

3. What is the difference between division and modulus in Python?

Division (/) gives the quotient (the result of division), while modulus (%) gives the remainder, highlighting the difference between division and modulus in Python.

4. Can I use modulus with floats in Python?

Yes, the modulus operator works with both integers and floating-point numbers. For example, 12.5 % 4.2 will return 4.1.

5. What happens when I divide by zero in modulus operation in Python?

Attempting to divide by zero using modulus will raise a ZeroDivisionError. Always check for a zero divisor before using modulus.

6. How does Python handle modulus with negative numbers?

Python ensures that the remainder in modulus with negative numbers has the same sign as the divisor. For example, -17 % 5 returns 3.

7. What is the purpose of math.fmod() in Python?

The math.fmod() function provides more precision than the % operator when calculating the modulus for floating-point numbers, especially with very small or large decimal numbers.

8. Can I calculate modulus for multiple numbers in Python?

Yes, you can calculate the modulus of multiple numbers using a function. For example, a custom function can return the modulus of several numbers sequentially.

9. What is the numpy.mod() function in Python?

The numpy.mod() function calculates the modulus of each element in two arrays element-wise, which is useful when working with large datasets.

10. How do I handle exceptions in Python when using modulus?

You can handle exceptions such as ZeroDivisionError and TypeError using try-except blocks. This ensures that your program doesn't crash when an error occurs during the modulus operation.

11. Can I use modulus to check if a number is even or odd?

Yes, you can use the modulus operator to check if a number is even or odd. If number % 2 == 0, the number is even, otherwise it’s odd.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.