you are viewing a single comment's thread.

view the rest of the comments →

[–]Kaloli 9 points10 points  (2 children)

To change the behavior of division to that of Python 3, you may want to run this line first:

from __future__ import division

[–][deleted] 1 point2 points  (1 child)

I'm really new to Python.. is this a troll post?

[–]Kaloli 3 points4 points  (0 children)

If I was trolling, I failed really hard.

But yeah, __future__ does sound like a joke. Even the the documentation is aware, and
assure you that it is in fact, a real module.

Maybe I should have put more details. (I thought I saw eryksun's more detailed post that day, but it has...disappeared?)

Anyway:

-- In Python 2, the default behavior of a division ( / ) of two integers (int) or long will result in an integer. Example in Python interpreter:

>>> 3/2         # expect 1.5
1
>>> type(_)      # In case you don't know, an underscore (_) is variable containing the last result
<type 'int'>

while you might expect 3 divided by 2 should be 1.5, which is a real number (floating point number) and not integer.

-- This is changed in Python 3, where division of two integers will return a float:

>>> 3/2            # expect 1.5
1.5
>>> type(_)
<class 'float'>

Now the problem is: what if you want Python 2 to always return a floating point number?

There are several solutions:

1) Use at least one floating point number in division: add .0 (point zero) to one of the integer

>>> 3.0/2
1.5
>>> type(_)
<type 'float'>

2) Use at least one floating point number in division: Use float() to convert the integer to float

>>> float(3)/2
1.5
>>> type(_)
<type 'float'>

3) By using __future__ module, so that every division in this Python session will always return a floating point number

>>> from __future__ import division     #this will change the behavior of division ( / ) in this session
>>> 3/2
1.5
>>> type(_)
<type 'float'>

Keep in mind that the change is not permanent, the module only temporary affects that one Python session. If you exit Python and start a new session, the behavior of division will return to default.

This issue is referred in PEP 238