Javatpoint Logo
Javatpoint Logo

Python Modulus Operator

Like other programming languages, the Python modulus operator does the same work to find the modulus of the given number. The operator is a mathematical symbol used to perform different operations such as (+, -, * /) addition, subtraction, multiplication, and division on the given two numbers to return the result in the form of an integer as well as the float number. An operator tells the compiler to perform certain actions based on the passed operator symbol to the given number.

Python Modulus Operator

Modulus Operator

Python Modulus Operator is an inbuilt operator that returns the remaining numbers by dividing the first number from the second. It is also known as the Python modulo. In Python, the modulus symbol is represented as the percentage (%) symbol. Hence, it is called the remainder operator.

Syntax

The below is the syntax that represent the modulus operator in Python language, it is used to get the remainder when we divide the first number with the second.

Here X and Y are two integer numbers, and the modulus (%) is used in between to get the remainder where the first number (X) is divided by the second number (Y).

For example, we have two numbers, 24 and 5. And we can get the remainder by using the modulus or modulo operator between the numbers 24 % 5. Here 24 is divided by 5 that returns 4 as the remainder, and 4 as the quotient. When the first number is completely divisible by another number without leaving any remainder, the result will be 0. For example, we have two numbers, 20 and 5. And we can get the remainder by using the modulus or modulo operator between the numbers 20 % 5. Here 20 is divided by 5 that returns 0 as the remainder, and 4 as the quotient.

Get the modulus of two integers numbers using while loop

Let's write a program to get the remainder of two numbers using the while loop and modulus (%) operator in Python.

Get_rem.py

Output:

Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
The result after performing modulus operator is: 37 % 5 = 2
The result after performing modulus operator is: 5 % 37 = 5
Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
The result after performing modulus operator is: 24 % 5 = 4
The result after performing modulus operator is: 5 % 24 = 5
Do you want to continue or not (Y / N)? Y
First number is: 37
Second number is: 5
The result after performing modulus operator is: 28 % 5 = 3
The result after performing modulus operator is: 5 % 28 = 5

Explanation:

  • while True: This creates an infinite loop. The code inside the loop will keep running until the loop is explicitly broken.
  • a = input('Do you want to continue or not (Y / N)? '): The user is prompted to enter 'Y' or 'N' to decide whether to continue or exit the program.
  • if a.upper() != 'Y': break: If the user enters anything other than 'Y' (case-insensitive), the loop is exited, and the program terminates.
  • a = int(input('First number is: ')) and b = int(input('Second number is: ')): The user is prompted to enter two integer numbers.
  • print("The result after performing modulus operator is: ", a, ' % ', b, ' = ', a % b): It calculates and prints the result of the modulus operation (a % b) for the first pair of numbers entered.
  • print("The result after performing modulus operator is:", b, ' % ', a, ' = ', b % a): It calculates and prints the result of the modulus operation (b % a) for the second pair of numbers entered.
  • The program will be asking the user weather we want to continue or we want to stop the program by giving the input like (Y/N), here Y is the input to continue the program and the 'N' is used to stop the program.

Get the modulus of two float numbers

Let's write a program to find the remainder of two floating point numbers using the modulus operator in Python.

Mod.py

Output:

First number: 40.5
 Second number: 20.5
Modulus of two float number is:  40.5 % 20.5 = 20.0

Explanation:

  • x = float(input('First number: ')): The client is provoked to enter a float number for the primary variable, and the information is put away in the variable x.
  • y = float(input('Second number: ')): The client is provoked to enter a float number for the subsequent variable, and the information is put away in the variable y.
  • res = x % y: The modulus activity is performed on x and y, and the outcome is put away in the variable res.
  • print("Modulus of two float numbers is: ", x, "%", y, " = ", res, sep=" "): The consequence of the modulus activity is printed with proper arranging, isolating the qualities by spaces (sep=" ").

Get the modulus of a negative number

Let's write a program to get the remainder of two negative number using while loop and modulus (%) operator in Python.

Mod.py

Output:

First number: -10
Second number: 3
Modulus of negative number is:  -10 % 3  =  2
Modulus of negative number is:  3 % -10  =  -7
 Do you want to continue (Y / N)? N

Explanation:

  • while True: Makes an endless circle. The code inside the circle will continue to run until the client chooses to exit by entering some different option from 'Y' when incited.
  • x = input('Do you need to proceed (Y/N)? '): The client is incited to enter 'Y' or 'N' to choose whether to proceed or leave the program.
  • if x.upper() != 'Y': break: Assuming that the client enters something besides 'Y' (case-uncaring), the circle is left, and the program ends.
  • x = int(input('First number: ')) and y = int(input('Second number: ')): The client is incited to enter two whole number numbers.
  • print("Modulus of negative number is: ", x, "%", y, " = ", x % y, sep=" "): It works out and prints the aftereffect of the modulus activity (x % y) for the primary sets of numbers entered.
  • print("Modulus of negative number is: ", y, "%", x, " = ", y % x, sep=" "): It ascertains and prints the aftereffect of the modulus activity (y % x) for the second sets of numbers entered.

Get the modulus of two numbers using fmod() function

Let's write a program to get the remainder of two float number using fmod() function in Python.

Fmod.py

Output:

Modulus using fmod() is: 3.5
 Modulus using fmod() is: 13.5
First number is 24
Second number is 5
Modulus of two numbers using fmod() function is 24  %  5  =  4.0

Explanation:

  • import math: This line imports the numerical module, which gives numerical capabilities, including fmod().
  • res = math.fmod(25.5, 5.5): The math.fmod() capability is utilized to compute the modulus of two drifting point numbers (25.5 and 5.5 for this situation), and the outcome is put away in the variable res.
  • print("Modulus utilizing fmod() is:", res): This line prints the aftereffect of the modulus activity determined utilizing math.fmod().
  • ft = math.fmod(75.5, 15.5): Like the principal model, it ascertains the modulus of two drifting point numbers (75.5 and 15.5) and stores the outcome in the variable ft.
  • print("Modulus utilizing fmod() is:", ft): This line prints the consequence of the second modulus activity.
  • x = int(input("First number is ")) and y = int(input("Second number is ")): The client is provoked to enter two whole number numbers, which are then changed over completely to numbers and put away in the factors x and y.
  • out = math.fmod(x, y): The math.fmod() capability is utilized again to compute the modulus of the two numbers entered by the client, and the outcome is put away in the variable out.
  • print("Modulus of two numbers utilizing fmod() capability is", x, " % ", y, " = ", out): This line prints the aftereffect of the modulus activity determined utilizing math.fmod() for the client entered whole numbers.

Get the modulus of n numbers using function

Let's write a Python program to find the modulus of n number using function and for loop.

getRemainder.py

Output:

Define a number till that you want to display the remainder 7
 Enter the second number 5
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
6 % 5 = 1
7 % 5 = 2

Explanation:

  • def getRemainder(n, k): This line characterizes a capability named getRemainder that takes two boundaries (n and k).
  • for I in range(1, n + 1):: This line begins a for circle that emphasizes from 1 to n (comprehensive).
  • rem = I % k: Inside the circle, the rest of I partitioned by k is determined and put away in the variable rem.
  • print(i, " % ", k, " = ", rem, sep=" "): This line prints the consequence of the modulus activity for every emphasis, showing the worth of I, the divisor k, and the determined remaining portion.
  • if __name__ == "__main__":: This line checks whether the content is being run as the primary program.
  • n = int(input("Define a number till that you need to show the rest of and k = int(input("Enter the subsequent number ")): The client is provoked to enter two whole number numbers, n and k.
  • getRemainder(n, k): The getRemainder capability is called with the client gave values to n and k. The capability works out and prints the rest of every cycle of the circle.

Get the modulus of given array using mod() function

Let's write a program to demonstrate the mod() function in Python.

Mod_fun.py

Output:

The modulus of the given array is [0 3 4 3]

Explanation:

  • import numpy as np: This line imports the NumPy library and allots it the moniker np. NumPy is a strong library for mathematical tasks in Python, and it gives effective exhibit tasks.
  • x = np.array([40, - 25, 28, 35]): Makes a NumPy cluster named x with the predetermined qualities.
  • y = np.array([20, 4, 6, 8]): Makes another NumPy cluster named y with the predetermined qualities.
  • print("The modulus of the given cluster is ", np.mod(x, y)): Calls the NumPy mod() capability, which performs component wise modulus procedure on comparing components of exhibits x and y. The outcome is printed utilizing print().

Get the modulus of two numbers using numpy.

Let's consider a program to import a numpy package from the Python library and then use the remainder function to get the modulus in Python.

Num.py

Output:

Modulus is 38 % 8 = 6

Explanation:

  • import numpy as np: This line imports the NumPy library and allots it the moniker np.
  • num = 38: Introduces the variable num with the worth 38.
  • num2 = 8: Instates the variable num2 with the worth 8.
  • res = np.remainder(num, num2): Calls the NumPy leftover portion() capability, which ascertains the rest of num is separated by num2. The outcome is put away in the variable res.
  • print("Modulus is", num, " % ", num2, " = ", res): Prints the aftereffect of the modulus activity utilizing print(). It shows the upsides of num, num2, and the determined remaining portion (res).

Exceptions in Python Modulus operator

In Python, when a number is divided by zero, it throws an exception, and the exception is called the ZeroDivisionError. In other words, it returns an exception when a number is divisible by a divisor that is zero. Therefore, if we want to remove the exception from the Python modulus operator, the divisor should not be zero.

Let's write a program to demonstrate the Python Exception in Modulus operator.

Except.py

Output:

The first number is: 24
The second number is: 0

Cannot divide a number by zero! So, change the value of the right operand.

As we can see in the above result, it displays, "Cannot divide a number by zero! So, change the value of the right operand". Hence, we can say, when we divide the first number by zero, it returns an exception.

Explanation:

  • x = int(input('The first number is: ')) and y = int(input('The second number is: ')): The client is provoked to enter two whole number numbers, which are then changed over completely to whole numbers and put away in the factors x and y.
  • attempt:: This starts the attempt block where the code that could raise an exemption is set.
  • print(x, ' % ', y, ' = ', x % y): Inside the attempt block, the code endeavors to ascertain and print the consequence of the modulus activity (x % y).
  • with the exception of ZeroDivisionError as blunder:: On the off chance that a ZeroDivisionError happens (i.e., assuming the client enters zero as the subsequent number), the code inside the aside from block is executed.
  • print('Cannot partition a number by nothing! ' + 'Thus, change the worth of the right operand.'): This line prints a blunder message demonstrating that division by zero isn't permitted and proposes changing the worth of the right operand.

Next TopicMATLAB vs. Python





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA