How do you divide a remainder in python?

How could I go about finding the division remainder of a number in Python?

For example:
If the number is 26 and divided number is 7, then the division remainder is 5.
[since 7+7+7=21 and 26-21=5.]

asked Apr 7, 2011 at 16:44

1

you are looking for the modulo operator:

a % b

for example:

>>> 26 % 7
5

Of course, maybe they wanted you to implement it yourself, which wouldn't be too difficult either.

wjandrea

24.5k8 gold badges53 silver badges73 bronze badges

answered Apr 7, 2011 at 16:45

Uku LoskitUku Loskit

39.7k9 gold badges87 silver badges91 bronze badges

2

The remainder of a division can be discovered using the operator %:

>>> 26%7
5

In case you need both the quotient and the modulo, there's the builtin divmod function:

>>> seconds= 137
>>> minutes, seconds= divmod[seconds, 60]

answered May 1, 2011 at 11:49

tzottzot

89.1k29 gold badges136 silver badges201 bronze badges

0

26 % 7 [you will get remainder]

26 / 7 [you will get divisor, can be float value]

26 // 7 [you will get divisor, only integer value]

wjandrea

24.5k8 gold badges53 silver badges73 bronze badges

answered Mar 17, 2016 at 22:14

1

If you want to get quotient and remainder in one line of code [more general usecase], use:

quotient, remainder = divmod[dividend, divisor]
#or
divmod[26, 7]

answered Feb 21, 2019 at 4:44

Alok NayakAlok Nayak

2,24220 silver badges28 bronze badges

1

From Python 3.7, there is a new math.remainder[] function:

from math import remainder
print[remainder[26,7]]

Output:

-2.0  # not 5

Note, as above, it's not the same as %.

Quoting the documentation:

math.remainder[x, y]

Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder[x, y] thus always satisfies abs[r]

Chủ Đề