Python Progress Bar Is Showing An Extra %

Question:

So I was following a YouTube tutorial for a progress bar in python and when its done, an extra "%" appears.
(NOTE: I changed a few variables in the code in order to have the needed product.)
Video link: https://www.youtube.com/watch?v=x1eaT88vJUA&ab_channel=NeuralNine

`

import math
import colorama

def progress_bar(progress, total, color=colorama.Fore.YELLOW):
    percent=100 * (progress / float(total))
    bar='■' * int(percent) + '-' * (100 - int(percent))
    print(color + f"r|{bar}| {percent: .0f}%", end="r")
    if progress==total:
        print(colorama.Fore.GREEN + f"r|{bar}| {percent:.0f}%", end="r")
numbers=[x * 5 for x in range(1000)]
results=[]
progress_bar(0, len(numbers))
for i, x in enumerate(numbers):
    results.append(math.factorial(x))
    progress_bar(i + 1, len(numbers))
print(colorama.Fore.RESET)

`

I tried to fix it on many different ways and the only one I found is to fully remove the "%" from the code.

Asked By: Luka

||

Answers:

Try the tqdm library instead of reinventing the wheel :). It’s very customizable.

Here is a demo:

enter image description here

Answered By: Nick

The problem is quite simple.

The program draws a bar on the same terminal line overwriting the previous text. Last 3 lines look like this:

yellow bar|  99%
yellow bar|  100%
 green bar| 100%_
                ^

As you see the last yellow line is longer that the final green line and the last character remains not overwritten.

One way to fix is not to draw the 100% line first in yellow and then in green.

Update: as noted by the OP, the length difference was due to a missing space and he fixed it that way.

Answered By: VPfB
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.