1. Home

Python Tutorials - Elevate Your Coding Skills with Comprehensive Tutorials

Discover Python tutorials covering everything from the basics to advanced topics. Whether you're new to programming or looking to level up your skills, our tutorials will guide you every step of the way

• 201 Lessons
• 33 Hours
145.Â

# Modulus in Python

Updated on 19/07/20246,342 Views

## Introduction

In this tutorial, we will delve deeply into Modulus in Python. This operation is fundamental to various mathematical and algorithmic tasks. Aimed at professionals looking to reskill or upskill, we will cover the syntax and real-world applications of the modulus operation, focusing on using a while loop to perform this operation. Understanding this concept is essential for anyone looking to master Python for professional growth.

## Overview

The modulus operation is a fundamental aspect of Python, used extensively in various applications. This tutorial will provide a comprehensive exploration of the Modulus in Python, starting with its definition and syntax, followed by its implementation using a while loop. We will break down each section into digestible parts, supported by bullets or tables for brevity, and summarize key points in paragraphs. By the end of this tutorial, you will have a thorough understanding of the modulus operation and its application in Python, enhancing your skills and knowledge as a Python professional.

## What is Modulus in Python?

Modulus is a mathematical operation that finds the remainder when one number (the dividend) is divided by another (the divisor). In Python, this is represented by the % symbol.

### Importance of Modulus

• Parity Checks: Determines if a number is even or odd. This is crucial in various applications, including computer graphics and digital signal processing.
• Cryptography: Used in various encryption algorithms to ensure the security of data transmission.
• String Operations: String rotation and text algorithms often use modulus to manipulate and analyze strings effectively.
• Hashing: Hash functions often utilize modulus to create hash values within a certain range, which is essential for efficient data retrieval in databases and other data structures.

### How it Works:

• Divides the left operand by the right operand.
• Returns the remainder of the division.
• Operator: The modulus operation is represented by %.

### Example:

7 % 3 gives the result as 1 as 7 divided by 3 is 2 with 1 as a remainder in Python.

### Uses:

• Time Complexity: The modulus operation has a time complexity of O(1), implying that it will take a constant time to be executed regardless of the input size. This makes it highly efficient for use in algorithms and applications that require optimal performance.
• Usage in Loops: The modulus operation is frequently used in loop control structures to determine loop termination conditions or to manipulate loop counters.
• Range Reduction: It is often used to reduce numbers to a specific range, for example, converting negative numbers to positive or limiting numbers to a specific range, which is useful in graphics programming and simulation.

## Modulus in Python Syntax

In Python, the modulus operator is represented by the percent sign %. It is used to find the remainder of the division of one number by another. Here's the syntax:

`result = dividend % divisor`

In the above syntax,

• dividend: This is the number you want to find the remainder of.
• divisor: This is the number by which you want to divide the dividend.

The % operator returns the remainder of dividing the dividend by the divisor. For example:

`result = 10 % 3 Â # result will be 1, because 10 divided by 3 is 3 with a remainder of 1`

You can use the modulus operator with variables as well:

Code:

`a = 15b = 7result = a % b Â # result will be 1, because 15 divided by 7 is 2 with a remainder of 1print(result)`

## Modulus Operator

Code:

`dividend = 17divisor = 5remainder = dividend % divisorprint(f"The remainder of {dividend} divided by {divisor} is {remainder}")`

Explanation:

In this example, we're using the modulus operator % to find the remainder when 17 is divided by 5, and the result is 2.

## Getting the Modulus of Two Integers Using while Loop

Code:

`# Input numbersdividend = int(input("Enter the dividend: "))divisor = int(input("Enter the divisor: "))# Initialize variables for the loopremainder = None# Perform the modulus operation using a while loopwhile dividend >= divisor:Â  Â  dividend -= divisorremainder = dividend# Print the resultprint(f"The remainder is {remainder}")`

Explanation:

• We take user input for the dividend and divisor.
• We initialize the remainder variable to None.
• We use a while loop to repeatedly subtract the divisor from the dividend as long as the dividend is greater than or equal to the divisor. This simulates the modulus operation.
• Once the dividend becomes less than the divisor, we exit the loop, and the value of dividend at that point is the remainder.
• We print the remainder as the result.

## Getting the Modulus of Two Float Numbers

Code:

`# Define two float numbersfloat_num1 = 17.5float_num2 = 4.2# Calculate the remainder using subtractionremainder = float_num1 - (float_num2 * (float_num1 // float_num2))print(f"The remainder of {float_num1} divided by {float_num2} is {remainder}")`

Explanation:

• We define two float numbers, float_num1 and float_num2.
• We calculate the remainder using subtraction by first finding how many times float_num2 fits into float_num1 using the floor division (//) operation.
• We then multiply float_num2 by the result of the floor division to get the nearest multiple of float_num2 that is less than or equal to float_num1.
• Finally, we subtract this multiple from float_num1 to obtain the remainder.

## Getting the Modulus of a Negative Number

Code:

`# Define a negative numbernegative_number = -17# Define a divisordivisor = 5# Calculate the modulusremainder = negative_number % divisorprint(f"The remainder of {negative_number} divided by {divisor} is {remainder}")`

Explanation:

• We define a negative number negative_number with a value of -17.
• We also define a divisor divisor with a value of 5.
• We calculate the modulus using the % operator, and the result will be the remainder when -17 is divided by 5.

## Getting the Modulus of Two Numbers Using fmod() Function

Code:

`import math# Define two float numbersfloat_num1 = 17.5float_num2 = 4.2# Calculate the modulus using fmod()remainder = math.fmod(float_num1, float_num2)print(f"The remainder of {float_num1} divided by {float_num2} is {remainder}")`

Explanation:

• We import the math module, which contains the fmod() function.
• We define two floating-point numbers, float_num1 and float_num2.
• We use the math.fmod() function to calculate the modulus of float_num1 divided by float_num2.
• Finally, we print the result.

## Getting the Modulus of n Numbers Using Function

Code:

`def getRemainder(x, y): Â  Â  Â Â Â  Â  for i in range(1, x + 1): Â  Â  Â  Â Â  Â  Â  Â  rem = i % y Â  Â  Â Â  Â  Â  Â  print(i, " % ", y, " = ", rem, sep = " ") Â  Â  Â Â if __name__ == "__main__": Â  Â  Â Â  Â  x = int(input ("Define a number till that you want to display the remainder ")) Â  Â Â  Â  y = int( input (" Enter the second number "))Â Â  Â  getRemainder(x, y)Â `

Explanation:

This Python code defines a function getRemainder that calculates and displays the remainder of each integer from 1 to a given number x when divided by another number y. Here's a step-by-step explanation of the code:

• The getRemainder function is defined with two parameters: x and y. These parameters represent the range of numbers and the divisor, respectively.
• Inside the function, there's a for loop that iterates from 1 to x (inclusive). This loop will go through each integer from 1 to x.
• For each integer i in the loop, it calculates the remainder when i is divided by y using the modulus operator %. The result is stored in the rem variable.
• The code then prints a message to display the current integer i, the modulus operator %, the divisor y, and the calculated remainder rem. The sep argument in the print function is set to a space to format the output.
• The if __name__ == "__main__": block is a common Python construct. It ensures that the code within the block only runs when the script is executed directly (not when it's imported as a module).
• Inside the if __name__ == "__main__": block:
• It takes user input for the value of x using input(). The user is asked to define a number up to which they want to display remainders.
• It also takes user input for the value of y using input(). The user is asked to enter the second number, which is the divisor.
• It then calls the getRemainder function with the provided values of x and y.
• The getRemainder function is called with the user-provided values, and it calculates and displays the remainders for each integer from 1 to x when divided by y.

## Getting the Modulus of Given Array Using mod() Function

Code:

`import numpy as np# Create a NumPy arrayarr = np.array([10, 20, 30, 40, 50])# Define the divisordivisor = 3# Calculate the modulus of the array elementsresult = np.mod(arr, divisor)print(f"The modulus of each element in the array with {divisor} is:")print(result)`

Explanation:

• We import the numpy library using the alias np.
• We create a NumPy array called arr containing some numbers.
• We specify the divisor (the number by which we want to calculate the modulus).
• We use the np.mod() function to calculate the modulus of each element in the array with respect to the divisor.
• Finally, we print the result.

## Get the modulus of two numbers using numpy

Code:

`import numpy as np# Define two numbersdividend = 17divisor = 5# Calculate the modulusremainder = np.mod(dividend, divisor)print(f"The remainder of {dividend} divided by {divisor} is {remainder}")`

Explanation:

• We import the numpy library using the alias np.
• We define the dividend and divisor as regular Python variables.
• We use the np.mod() function to calculate the modulus of the dividend and divisor.
• Finally, we print the result.

## Exceptions in Python Modulus Operator

Code:

`try:Â  Â  dividend = int(input("Enter the dividend: "))Â  Â  divisor = int(input("Enter the divisor: "))Â  Â  remainder = dividend % divisorÂ  Â  print(f"The remainder of {dividend} divided by {divisor} is {remainder}")except ZeroDivisionError:Â  Â  print("Error: Division by zero is not allowed.")except ValueError:Â  Â  print("Error: Please enter valid integer inputs.")except Exception as e:Â  Â  print(f"An unexpected error occurred: {e}")`

Explanation:

• We use a try block to enclose the code that may potentially raise exceptions.
• Inside the try block, we take user input for the dividend and divisor and perform the modulus operation.
• We use except blocks to handle specific types of exceptions:
• ZeroDivisionError is raised when attempting to divide by zero.
• ValueError is raised when the user enters input that cannot be converted to integers.
• The final except block is a catch-all for unexpected exceptions and will print an error message along with the specific error message associated with the exception.

## Conclusion

Throughout this tutorial, we have examined the modulus operation in Python in detail. From understanding its fundamental concept and syntax to implementing it using a while loop, we have covered various aspects that are crucial for any Python professional. Understanding the modulus operation is essential for various mathematical and algorithmic applications in Python.

As professionals looking to reskill or upskill, mastering such fundamental concepts is key to enhancing your proficiency and versatility in Python.

As we conclude, it is important to practice implementing the modulus operation in different scenarios to solidify your understanding. Additionally, consider taking upskilling courses from upGrad to further advance your knowledge and skills in Python and other relevant areas. upGrad offers a wide range of courses tailored for working professionals, ensuring you stay competitive in your field. Remember, continuous learning and practice are the keys to success in any profession.

## FAQs

1. What is the significance of the modulus operator in Python?

The modulus operator in Python is fundamental for various applications, including algorithms, data manipulations, and simple arithmetic tasks. It is used to determine the remainder of a division operation, which is essential for parity checks, cryptography, hashing, and manipulating data structures like circular arrays.

2. Can the modulus operator be used with floating-point numbers?

Yes, the modulus operation is valid for floating-point numbers in Python. However, it may yield unexpected results because of the way in which floating-point numbers are represented in computers. It's essential to understand the behavior of floating-point arithmetic to interpret the results correctly.

3. How does a while loop facilitate calculating the modulus of two integers?

A while loop allows you to repeatedly perform the modulus operation under specific conditions, which is useful for specific algorithms that require iterative calculations. It can help in scenarios where you need to compute the modulus of numbers in a sequence or as part of a larger algorithm.

4. Are there any alternatives to the modulus operator for obtaining the remainder?

Yes, Python provides the divmod() function, which returns a pair of numbers (a tuple) representing the quotient and the remainder when dividing two numbers. For example, divmod(a, b) will return a tuple (q, r) where q is the quotient a//b and r is the remainder a%b.

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working â€¦Read More

###### Need More Help? Talk to an Expert
+91
*
By clicking, I accept theT&Cand
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.

Talk to our experts. Weâ€™re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...