0

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.

AlmostGr
  • 89
  • 8

4 Answers4

1

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

Akhil Job
  • 419
  • 6
  • 18
  • Thanks all, your help is very much appreciated. As I'm a beginner this is new to me, and I definitely have to look at some of my other code, where I might have made the same mistakes by making divisions. – AlmostGr Oct 03 '16 at 14:13
1

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

Michel Touw
  • 626
  • 6
  • 15
1

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.

0

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.

Community
  • 1
  • 1
imant
  • 597
  • 5
  • 15