-1

So I'm trying to make kind of a progress bar in Python, and in a for-loop I wrote this:

print(i, end='\r', flush=True)
sleep(0.1)

so it's supposed to write 0 then 1, etc. But instead I get something like:

0123456789101112131415161718192021222324252627282930313233343536373839

What am I doing wrong?

Update: I am using Spyder.

Here is the entire loop:

for i in range(it):
    _sum += z**i * f(i)
    print(i, end='\r', flush=True)
    sleep(0.1)
s-jevtic
  • 51
  • 1
  • 6

1 Answers1

0

This works for me as intended, it is hard to tell what the problem with your code was, since you only posted fractional code

If you are using a for loop with a list, then it must be formatted properly. use a list if you plan to use out of order numbers.

import time
numbers = ['1','2','3','4','5','6','7']

for number in numbers:
    print(number, end='\r', flush=True)
    time.sleep(0.5)

If you want a sequential enumeration, then you can use a canonical expression:

for number in range(20):
    print(number, end='\r', flush=True)
    time.sleep(1)

Or if you want to use a while loop

import time
n = 0
while n <= 15:
    n += 1
    print(n, end='\r', flush=True)
    time.sleep(0.5)

All three loops work as intended and in almost the same way

Enrique Bruzual
  • 351
  • 1
  • 3
  • 16
  • The canonical way of doing it is `for i in range(n):`, `i` is the number and `n` is the number of iterations. – iz_ Mar 17 '19 at 03:42
  • Right, in my example the numbers are sequential in the list, so canonical expression would works, but if you notice his example is a long random list thus your approach would not work. But sure let's add it – Enrique Bruzual Mar 17 '19 at 03:49
  • 1
    OP's list does not seem random at all to me, it's `0` then `1` then `2` all the way up to `37` then `38` then `39`. – iz_ Mar 17 '19 at 03:55
  • You are right. Well, if he want to use an out of order list, then he has an example to choose from. cheers – Enrique Bruzual Mar 17 '19 at 03:59
  • i can confirm what @Tomothy32 said. It's literally printing all the numbers without clearing the previous ones. – s-jevtic Mar 19 '19 at 00:20
  • Since you are posting on my answer, did you try any of the examples I posted? they all work form me – Enrique Bruzual Mar 19 '19 at 02:06