Python: how to create a progress bar

In this article we will see how to create a progress bar with Python.

It is a question of defining a segment of a determined width by placing a fill character on the left and the current percentage of progress on the right.

We can implement the following solution:

from time import sleep


def progress(percent=0, width=30):
    left = width * percent // 100
    right = width - left
    print('\r[', '#' * left, ' ' * right, ']',
          f' {percent: .0f}%', sep='', end='', flush=True)


for i in range(101):
    progress(i)
    sleep(0.1)

To simulate an operation in progress, in this case we use the sleep() function to ensure that the progression from 0 to 100 is not immediate. In reality the feed rate will be determined by the time each operation in the loop will be completed.

Back to top