python integer division error - modulo by zero - BUT divisor != 0
Solution 1
Probably you are using Python 2.x
, where x / y
is an integer division
.
So, in the below code: -
( 20 + ( 0 / 19 ) ) ) / ( 1 / 19 )
1 / 19
is an integer division
, which results in 0
. So the expression is essentially same as: -
( 20 + ( 0 / 19 ) ) ) / 0
Now you see where the error comes from.
You can add following import in you python
code, to enforce floating-point division: -
from __future__ import division
Or you could cast one of the integers to a float, using either float()
or just by adding .0
to the initial value.
Solution 2
from __future__ import division
and than do your calculation
it will cause the division to return floats
ccdpowell
Engineer turned Salesperson turned Entrepreneur turning programmer.
Updated on July 14, 2022Comments
-
ccdpowell almost 2 years
I am new to doing simple math using python, so sorry if this is a silly question.
I have 8 variables that are all set to integers and these integers are used when performing a simple calculation.
a = 0 b = 17 c = 152 d = 1 e = 133 f = 19 g = 20 h = 0 answer = ( ( ( a / f ) + b + c ) - ( g + ( h / f ) ) ) / ( d / f ) print answer
When I run this code, I get the error, ZeroDivisionError: integer division or modulo by zero.
I have read about this error and all documentation points towards my divisor being zero, but if I print this with the numbers as strings in place of the variables, I get:
( ( ( 0 / 19 ) + 17 + 152 ) - ( 20 + ( 0 / 19 ) ) ) / ( 1 / 19 )
Nowhere in this statement is the divisor zero.
Please let me know how I need to change my expression in order to get the answer 2831. Note that I can change the type of the variables to a float or other. Thank you for your help!