Change language

Python Modulo &operator%

The Python module operator (%) is used to get the remainder of a division. Modulo operation is supported for integers and floating point numbers.

The syntax for the modulo operator is a% b . Here "a" ÷nd, and "b" ÷r. Result &this is the remainder of dividing a by b.

If both "a" and "b" are integers, then the remainder is also an integer. If one of them is a floating point number, the result is also a floating point number.



Sample Python modulus statement

Let’s look at some examples of a modulo statement.

1. Modulo integers

""" 10% 3 1""" 2% 20""" 

2. Modulo with float

""" 9% 3.0 0.0""" 10% 3.0 1.0""" 

3. Modular with user input.

 x = input ("Please enter first number:") fx = float (x) y = input ("Please enter first number: ") fy = float (y) print (f’ {x}% {y} = {fx% fy}’) 

Python Modulo operator

When we receive user input, it is in the form of a string. We use the built-in float () function to convert them to floating point numbers. This is why the remainder is 1.0 and not 1.

4. Example ZeroDivisionError

If the divisor is 0, the modulo operator will throw ZeroDivisionError . We can use a try-except block to catch the error. 

 a = 10.5 b = 0 try: print (f’ {a}% {b} = {a% b} ’) except ZeroDivisionError as zde: print ("We cannot divide by 0") 

 ZeroDivisionError



5. Modulo negative numbers

The Python module statement always returns a remainder that has the same sign as the divisor. This can lead to confusion in the output.

""" -5% 3 1""" 5% -3 -1""" -10% 3 2""" 
  • -5% 3 = (1-2 * 3)% 3 = 1
  • 5% -3 = (-1 * -2 * -3)% 3 = -1
  • -10% 3 = (2-4 * 3)% 3 = 2

6. Python Modulo math.fmod ()

The behavior of the% operator with negative numbers is different from the behavior of the C library. If you want modulo operations to behave like C programming, you should use the fmod () function of the math module. This is the recommended function for getting floating point numbers modulo.

""" import math"" & gt; math.fmod (-5, 3) -2.0""" math.fmod (5, -3) 2.0""" math.fmod (-10, 3) -1.0""" 
  • fmod (-5, 3) = fmod (-2 -1 * 3, 3) = -2.0
  • fmod (5, -3) = fmod (2-1 * -3, -3) = 2.0
  • fmod (-10, 3) = fmod (-1-3 * 3, 3) = -1.0

Modulo operator overloading

We can modulo operator overloading by implementing __mod __ () in our class definition.

 class Data: def __init __ (self, i): self.id = i def __mod __ (self, other): print (’ modulo function called’) return self.id% other .id def __str __ (self): return f’Data [{self.id}] ’d1 = Data (10) d2 = Data (3) print (f’ {d1}% {d2} = {d1% ​​d2}’ ) 

Output:

 modulo function called Data [10]% Data [3] = 1 

Briefly about the problems of floating point arithmetic

We use a binary format to store values ​​in computers. As far as fractions are concerned, in most cases we cannot represent them exactly as binary fractions. For example, 1/3 cannot be represented in exact binary format, and it will always be an approximate value.

This is why you can get unexpected results when doing floating point arithmetic. This is clear from the output of the modulo operations below.

""" 9.6% 3.2 3.1999999999999993 

Output should be 0 because 3.2 * 3 equals 9.6. But floating point fraction values ​​are not represented exactly, and approximation causes this error. This is also seen in this example.

""" 9.6 == 3.2 * 3 False""" 

Therefore, you must take extra care when working with floating point numbers. It is advisable to round and then compare only two floating point numbers.

""" round (9.6, 3) == round (3.2 * 3, 3) True 



Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically