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?

user1695758
  • 173
  • 1
  • 3
  • 14

3 Answers3

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)
Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
  • I upgraded to Python3 8 months ago and STILL have to debug `SyntaxError`s from my slapped-together `print value` statements. – Adam Smith Feb 20 '14 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 '14 at 19:32
  • For the sake of learning @mhlester? – Travis Griggs Feb 20 '14 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 '14 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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
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
mhlester
  • 22,781
  • 10
  • 52
  • 75