Lio Elbammalf Lio Elbammalf - 2 months ago 6
Python Question

Python: 4/5=0.0. Float declaration missing?

Apologies if this has already been asked but why does this:

a=4
b=5
c=float(a/b)

print c


Gives

>>>>
0.0


rather than 0.8?

Answer

In Python 2, division between 2 integers will return an integer (rounding to the closest integer to 0), in this case, 0. Your code is basically float(0) which is 0.0.

You would need to change one of your values to a float first if you want to return a float.

This behavior is changed in Python 3, where division between 2 integers will return a float, 0.8 in this case.