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!
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.
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