Modulo Operator in Python
Modulo Operator ‘%’ is used to find the remainder between the division of two numbers.
Syntax – A % B
Where A is the dividend (The number that is being divided)
B is the divisor (The number that is going to divide the dividend)
And the result of this operation will yield the remainder obtained on dividing A by B.
A = float(input("Enter the dividend: ")) B = float(input("Enter the divisor: ")) result = float(A%B) print(f"result = {result}")
Now the result will yield the remainder of the two numbers given as input.
Enter the dividend: 25 Enter the divisor: 4 result = 1.0
Some Cases
Case 1: When Dividend is Zero
Whenever we divide 0 by a number (given it is not 0) then we get 0 as the result. So as no remainder is obtained then if we do 0%x (where x is some number other than 0) we will get 0 as the result.
Enter the dividend: 0 Enter the divisor: 5 result = 0.0
Case 2: When Divisor is Zero
The result of dividing some numbers by zero is not defined. So when we run the same code with 0 as the divisor then we get Zero Division Error.
Enter the dividend5 Enter the divisor0 Traceback (most recent call last): line 3, in <module> result = float(A%B) ZeroDivisionError: float modulo
Case 3: When Divisor is bigger than Dividend
We will get the same number as the result.
Enter the dividend3 Enter the divisor9 result = 3.0
Two most common use of modulus operator in Python
Here we are showing the common use of this operator.
To check whether a number x is divisible by some other number y
If x is divisible by y then the result of x%y will be 0.
x = float(input("Enter x: ")) y = float(input("Enter y: ")) result = float(x%y) if result == 0: print("x is divisble by y") else: print("x is not divisible by y")
OUTPUT
Enter x: 25 Enter y: 5 x is divisible by y
Whether a given number is even or odd using modulo operator
If A is even then A%2 will be equals to zero otherwise it is odd.
A = float(input("Enter x:")) result = float(A%2) if result == 0: print("X is even") else: print("X is odd")
OUTPUT
Enter x:25 X is odd
Thank you. If you liked my content leave a comment below.
Leave a Reply