What Does % Mean In Python

The % is an operator in python which we used in solving mathematical expressions. The % operator returns the remainder by dividing a Left-Hand Side value by the Right-Hand Sides value.

The % is known as a module operator in python which is used to divide 2 operators and returns a reminder as a result.

Syntax

Value1 % value2

Example 1

6 % 8

You can write an expression like the above in your python program.

Output

6

Example 2

for number in range(10, 20):
    if(number % 2 != 0):
        print(number)

In the above example, we printed the numbers using for loop with the if condition. In the if condition we said that if a reminder is 2 and not equal to 0 then print the numbers. 

The above code will print the numbers from 10 to 20 in a discontinuous way.

Output

11
13
15
17
19

Example 3

x = 10
y = 0
  
# exception handling
try:
    print(x, 'mod', y, '=',
          x % y, sep = " ")
      
except ZeroDivisionError as err:
    print('Cannot divide' + 
          'Change the value of the y.')

You can see the above example, we tried exception handling using the % operator, we declared 2 variables x and y then used a try statement that will print the mod value but just because the value of y is 0 so it wouldn’t be able to calculate the mode value.

Note: We cannot calculate the mod(%) value with 0. 

Output

Cannot divideChange the value of the y.

Conclusion

In this tutorial, we talked about the % operator python, we also practiced some examples using % in different scenarios.

Hope you like the tutorial if you have any queries regarding this tutorial feel free to ask below. Thanks for reading.

Leave a Comment