AlmostGr
AlmostGr

Reputation: 99

division gives 0 in loop, why?

the code below gives me 0% for each 20th iteration, instead of the actual percentage I would like it to show.

n=100
for i in range(n):
    if i% 20 ==0:
        print str(i/n*100) + '%, Progress'

Results:

0%, Progress
0%, Progress
etc.....

I must be missing something really simple. Thank you.

Upvotes: 0

Views: 129

Answers (4)

imant
imant

Reputation: 627

In each iteration i/n*100 gets rounded down to the nearest integer (this is how the division operator works on integers in python2).

You could either use explicit casting to float() or execute from __future__ import division beforehand. This would prevent the division operator from rounding down automatically.

Here you can find a detailed description of a similar problem.

Upvotes: 0

n=100 for i in range(n): print(i); if i% 20 ==0: print str((float(i)/float(n))*100) + '%, Progress'

for python i/n is an (int)/(int) according to your variable declaration. so ti tries to give an int answer for i/n which is always 0.

Upvotes: 1

Michel Touw
Michel Touw

Reputation: 626

Division automatically rounds down to the nearest integer. What happens in your code is: i = 20 n = 100

i/n = 20/100, which becomes 0. Then (i/n)*100 = 0*100 = 0. You could solve this by first multiplying i by 100 and then dividing by n: i*100/n

Upvotes: 1

Akhil Job
Akhil Job

Reputation: 419

change the division to i/(float)n*100 so that the resulting output will be formatted to decimal points by the python interpreter.

Upvotes: 1

Related Questions