This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by lashley831
over 8 years

Percent calculation

What are the rules for percentage calculation in Python?

When I write: tip = 15/100 print tip

It spits out 0. If, however I add a .0 after the 15, it gives me 0.15. Why does it have to be written like that specifically?

Answer 55a4cffad3292f1cff000436

1 vote

Permalink

@lashley831

The following statement performs division on two operands of type int

tip = 15/100

In Python 2.x, integer division produces an int result, rather than a float result. Fractional parts are discarded.

If you have two ints, at least one of them must be converted to a float if you want to perform float division on them. If you are working with numerical constants, you can include a decimal point, as you pointed out in your post. For any expression, you can use the float built in function to perform the conversion of one or both operands, prior to division …

a = 7
b = 11
c = float(a) / float(b)

With the tip calculation, this will work …

tip = float(15) / 100

… as will this …

tip = 15 / float(100)
points
Submitted by Glenn Richard
over 8 years