Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - throw exception if division has remainder?

Tags:

python

In Python, you can do:

assert a % b == 0
c = a // b

Is there a shorthand for this? In other words, a way to do integer division that throws an exception if there is a remainder?

The reason I ask is that it would be convenient in situations like this:

count = len(self.rawr.foo) / self.this.is.a.long.variable

Right now I have to make temporary variables:

a = len(self.rawr.foo)
b = self.this.is.a.long.variable
assert a % b == 0
count = a // b

which does not seem very pythonic.

I know that some languages like C# have ways to do safe division; strange that Python doesn't.

like image 958
Billy Avatar asked Apr 13 '14 22:04

Billy


People also ask

How do you get the remainder of a division in Python?

The Python modulo operator calculates the remainder of dividing two values. This operator is represented by the percentage sign (%). The syntax for the modulo operator is: number1 % number2. The first number is divided by the second then the remainder is returned.

How do you check if a remainder is zero in Python?

In Python, the remainder is obtained using numpy. ramainder() function in numpy. It returns the remainder of the division of two arrays and returns 0 if the divisor array is 0 (zero) or if both the arrays are having an array of integers. This function is also used on individual numbers.

How do you find the quotient and remainder in Python?

We can divide two numbers using the '//' operator one can derive the quotient. The remainder is calculated using the '%' operator in Python.

How do you divide without a remainder in Python?

Use the floor division operator // to divide without a remainder, e.g. result_1 = 25 // 4 . The floor division operator will always return an integer and is like using mathematical division with the floor() function applied to the result.


1 Answers

You could do:

count, rem = divmod(len(self.rawr.foo), self.this.is.a.long.variable)
assert not rem # or `assert rem == 0`
like image 55
Tim Peters Avatar answered Sep 30 '22 18:09

Tim Peters