For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
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!”
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.
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.
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:
“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!”
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.
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:
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:
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:
These examples give you a solid understanding of how the modulus operator works in Python across different data types.
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.
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:
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:
Also Read: Difference Between Function and Method in Python
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:
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:
Also Read: Libraries in Python Explained: List of Important Libraries
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:
We’ve covered several practical ways to use the modulus in Python with example.
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.
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:
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.
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:
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:
To ensure smooth handling of modulus operations and prevent your program from crashing due to exceptions, follow these best practices:
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.
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.
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.
Division (/) gives the quotient (the result of division), while modulus (%) gives the remainder, highlighting the difference between division and modulus in Python.
Yes, the modulus operator works with both integers and floating-point numbers. For example, 12.5 % 4.2 will return 4.1.
Attempting to divide by zero using modulus will raise a ZeroDivisionError. Always check for a zero divisor before using modulus.
Python ensures that the remainder in modulus with negative numbers has the same sign as the divisor. For example, -17 % 5 returns 3.
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.
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.
The numpy.mod() function calculates the modulus of each element in two arrays element-wise, which is useful when working with large datasets.
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.
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.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.