Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Progress Bar Is Showing An Extra %

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)

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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:

if progress < total:
    print(colorama.Fore.GREEN + f"\r|{bar}| {percent:.0f}%", end="\r")
else:
    print(color + f"\r|{bar}| {percent: .0f}%", end="\r")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading