3

I just started learning python, and I wrote these three lines of code:

points = 49
total = points / 50 * 500 + 40
print "omg wtf ", total

And I expected the output to be something like 530, but instead, no matter what I do, I keep getting 40. I tried initializing total to 0, casting the assignment to an int, I threw in a buttload of parentheses, but nothing works. I'm so baffled... Can someone help me / tell me what the heck is going on?

1
  • 3
    49 / 50 is 0, floor division on integers.
    – Martijn Pieters
    Feb 20, 2014 at 19:10

3 Answers 3

7

"I just started learning Python..." Awesome. I did so myself 1.5 years ago. It's a fun language and a good community.

My strong suggestion is that you just switch to python3. I'm much happier myself.

In that case you would have seen 530, just like you expected. In that case, you would have changed your last line to include parentheses, e.g:

print("omg wtf", total)
4
  • I upgraded to Python3 8 months ago and STILL have to debug SyntaxErrors from my slapped-together print value statements.
    – Adam Smith
    Feb 20, 2014 at 19:24
  • 1
    @TravisGriggs, While a great suggestion, I'd point out that there are many environments where upgrading to 3 is simply not possible
    – mhlester
    Feb 20, 2014 at 19:32
  • For the sake of learning @mhlester? Feb 20, 2014 at 19:42
  • 1
    certainly for the sake of learning in a vacuum use 3. but if for instance OP is learning a different program that uses an embedded python for scripting, you're stuck with whatever it uses
    – mhlester
    Feb 20, 2014 at 19:47
5

In Python 2, using the division operator / on two integers returns an integer by truncating the result. So 49/50 evaluates to zero.

My recommendation is to always use from __future__ import division at the top of every piece of code you write, which removes this confusing behavior.

You can also fix it by using floats, for instance by using points be 49.0, or by doing total = float(points) / 50 * 500 + 40. However, these require you to remember to do that for every calculation. Because the behavior has been changed in Python 3, the forward-looking way is to use from __future__ import division to make float division the default.

1
  • Thanks. Can you refer me to some good python tutorials? The ones I've looked at aren't very descriptive... Feb 20, 2014 at 19:21
2

Python 2.7 and earlier use integer math when the inputs are integer. so 49 / 50 = 0. Make one a float to get the output you want:

points = 49.  # <-- adding a dot

or

points = float(49)  # wrapping in float()

Now you get:

>>> total = points / 50 * 500 + 40
>>> print "omg wtf ", total
530.0

Not the answer you're looking for? Browse other questions tagged or ask your own question.