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.
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.
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.
We can divide two numbers using the '//' operator one can derive the quotient. The remainder is calculated using the '%' operator 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.
You could do:
count, rem = divmod(len(self.rawr.foo), self.this.is.a.long.variable)
assert not rem # or `assert rem == 0`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With