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, wherex / yis aninteger division.So, in the below code: –
1 / 19is aninteger division, which results in0. So the expression is essentially same as: –Now you see where the error comes from.
You can add following import in you
pythoncode, to enforce floating-point division: –Or you could cast one of the integers to a float, using either
float()or just by adding.0to the initial value.