Simple math in python won't work?

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 was expecting the result to be something like 530, but instead, no matter what I do, I keep getting 40. I tried initializing the final value 0, discarding the int assignment, I was throwing in parentheses, but nothing works . I am so puzzled ... Can someone help me / tell me what's going on?

+3
source share
3 answers

"I just started learning Python ..." Amazing. I did it myself 1.5 years ago. It is a fun language and a good community.

My strong suggestion is that you just switch to python3. I am much happier than myself.

530, . , , :

print("omg wtf", total)
+6

Python 2 / , . , 49/50 .

- from __future__ import division , , .

, float, , points be 49.0 total = float(points) / 50 * 500 + 40. , . Python 3, from __future__ import division, .

+5

Python 2.7 and earlier use integer math when the inputs are integer. therefore 49 / 50 = 0. Make one float to get the desired result:

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
+2
source

All Articles