To implement a progress bar in Python, write a function that takes its arguments the progress in percents, and the width of the bar. Then, based on the percentage:
- Calculate the number of hashtags on the left.
- Calculate the number of spaces on the right.
- Print the hashtags, spaces, and the percentage on the same line.
If you only came for the code, here it is with example use:
from time import sleep def progress(percent=0, width=40): left = width * percent // 100 right = width - left tags = "#" * left spaces = " " * right percents = f"{percent:.0f}%" print("\r[", tags, spaces, "]", percents, sep="", end="", flush=True) # Example run for i in range(101): progress(i) sleep(0.05)
This outputs a progress bar that fills up among the percentage.
[################################# ] 75%
Next, let’s go through the code in detail to understand what happens.
Implementation of Progress Bar in Python
Let’s start with the 4th and 5th lines:
left = width * percent // 100 right = width - left
Here the left is the number of hashtags given the progress percentage. For example, at 30% it is (40 * 30) / 100 = 12. The right is the number of spaces on the right-hand side. In case of 30% progress it is 40 – 12 = 28.
On lines 7 and 8, we multiply a hashtag/empty space by the number of times they should occur:
tags = "#" * left spaces = " " * right
On line 10, we format the number of percents to be displayed in the mix:
percents = f"{percent:.0f}%"
On line 12, we put it all together and print the hashtags, spaces, and percentages. There is so much going on in this line.
print("\r[", tags, spaces, "]", percents, sep="", end="", flush=True)
Let’s take a deeper look at each part of the line:
- “\r[“ always prints “[“ on the same place in the line. The \r is called a carriage return. It always goes back to the same starting point of the line.
- Then we add the tags, spaces, closing square bracket, and the percentage. This is all we need for the progress bar itself.
- Next we specify an optional parameter sep. It acts as the separator between each printed item. By default it is a space. But we do not want a space so we specify it an empty string “”.
- Then we tweak the end argument. By default, Python print() adds a line break at the end of the line. But this is not what we want. So we also specify the end as an empty string.
- Finally, the flush is set True. By default, Python does not display consecutive print() calls if they do not have a line breaks. This is due to buffering, which optimizes performance.
This is all there is to it.
Now you should have a basic idea of how the progress bar code works in Python.
Conclusion
Thanks for reading.
Happy coding!