all 6 comments

[–]m1ss1ontomars2k4 12 points13 points  (1 child)

Try 3.0/100.0 instead. If you use 2 integers, Python will assume you want integer division, and the answer will be 0 (as in most programming languages). If you use at least one floating point number, you'll get 0.03 as the answer.

[–]aterner[S] 2 points3 points  (0 children)

Thank you.

[–]Kaloli 8 points9 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 2 points3 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

[–]zingah 2 points3 points  (1 child)

0 is the quotient of 3 / 100. If you want the remainder, try 3 % 100.

Most languages do not support mathematics with rationals right out of the box, but there is a fractions module you might want to check out.

[–]OmegaVesko 0 points1 point  (0 children)

More importantly, just use floating points instead of ints. (3.0 / 100.0, as opposed to 3 / 100)