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}’) `

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") `

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

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

Best laptop for Excel

\$

Best laptop for Solidworks

\$399+

Best laptop for Roblox

\$399+

Best laptop for development

\$499+

Best laptop for Cricut Maker

\$299+

Best laptop for hacking

\$890

Best laptop for Machine Learning

\$699+

Raspberry Pi robot kit

\$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

PythonStackOverflow

Check if one list is a subset of another in Python

PythonStackOverflow

How to specify multiple return types using type-hints

PythonStackOverflow

Printing words vertically in Python

PythonStackOverflow

Python Extract words from a given string

PythonStackOverflow

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

PythonStackOverflow

Python os.path.join () method

PythonStackOverflow

Flake8: Ignore specific warning for entire file

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