Get Division Remainder in Python

Get Division Remainder in Python

Muhammad Waiz Khan Apr-12, 2022 Dec-15, 2021 Python Python Math
  1. Get Division Remainder in Python Using the Modulo % Operator
  2. Get Division Remainder in Python Using the divmod() Function
  3. Get Division Remainder in Python Using User-defined Function

This article will look into the different methods to get the remainder of the division in Python. If we divide 10 by 3, then the remainder should be 1, and for 10 / 2, the remainder will be 0.

We can use the following methods to get the remainder of the division in Python.

Get Division Remainder in Python Using the Modulo % Operator

The most commonly used and simple method to get the remainder is by using the modulo % operator. Suppose we want to get the remainder of a / b, we can use the modulo operator like a % b, and it will return the remainder after performing the division operation.

The below example code demonstrates how to use the modulo % operator to get the remainder of the division in Python.

rem = 14 % 5
print(rem)

Output:

4

Get Division Remainder in Python Using the divmod() Function

We can also use Python’s divmod() function to get the remainder of the division. The divmod(x, y) function takes two inputs, x as dividend and y as the divisor, and returns quotient and remainder as output.

The below example code demonstrates how to get remainder after the division using divmod() function in Python.

quot, rem = divmod(31, 7)
print(rem)

Output:

3

Get Division Remainder in Python Using User-defined Function

We can also define our own function to get the remainder of the division in Python. We can get the remainder of the division using a user-defined function in the following way.

def get_remainder(num, div):
  rem = num - (num // div * div)
  return rem

print(get_remainder(17, 3))

Output:

2

Related Article - Python Math

  • Calculate Factorial in Python
  • Calculate Inverse of Cosine in Python
  • Calculate Modular Multiplicative Inverse in Python
  • Fit Poisson Distribution to Different Datasets in Python
  • Reduce Fractions in Python
  • Define an Infinite Value in Python