-2

That's just basic math, 1/2 = 0.5, but it seems on Python the result is 0?

I thought that the result is in int format, but I've also tried float(1/2) and the result is still the same. Does anyone know why is this happening?

(Sorry for the bad English, not my native language. Also, I just got learning Python:D)

  • 3
    Note that `float(1/2)` is the same as `float( evaluate 1/2 in integer arithmetic)` which is `float(0)`. I use `1.0 / 2` for something like this. – Edmund Price Oct 14 '16 at 14:25
  • In Python 2 if you divide an int by another int using `/` then integer division is used. In Python 3 you'd get float division unless you used the floor division operator `//`. You can get the Python 3 behaviour in Python 2 by including `from __future__ import division` at the top of your script. BTW, if you're just learning Python now you should probably be learning Python 3 unless there's some _major_ reason forcing you to use Python 2. – PM 2Ring Oct 14 '16 at 14:27
  • Also see http://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-in-python-division-keeps-rounding – PM 2Ring Oct 14 '16 at 14:30
  • This is a bug with older versions of Python. Try installing a [newer version](https://www.python.org/downloads/release/python-352/). – asmeurer Oct 14 '16 at 19:02

1 Answers1

0

try

float(1) / float(2)

Hope this helps

Luke.py
  • 965
  • 8
  • 17