Nandakumar Edamana
Nandakumar Edamana

Reputation: 768

Finding percentage in Python

A question for python beginners:

Anybody knows 20/200*100 is 10. But python says 0!

Check this code:

print 20/200*100

Do you know why this happens and how to solve this problem?

Upvotes: 0

Views: 303

Answers (3)

user9283885
user9283885

Reputation: 13

print (20/float(200)*100)

use float(x) to the numerator or the denominator if the answer is going to be decimal number

Upvotes: 0

Nandakumar Edamana
Nandakumar Edamana

Reputation: 768

Why this happens:

20/200 is 0.01

0.01 -> int = 0

0*100 = 0

How to solve:

Use:

print float(20)/200*100

or:

print 20.0*100/200

But note that it won't support variables.

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304147

In Python2, / is a truncated division if both arguments are int

You can just use a float literal instead of converting an int to a float

>>> 20/200.0*100
10.0

or multiply by 100.0 first if the other two variables are int

>>> 100.0*20/200
10.0

Upvotes: 1

Related Questions