How to Create a Progress Bar in Python Easily
You can create a progress bar in Python by printing characters in a loop to show progress or by using the
tqdm library for a ready-made, easy-to-use progress bar. The tqdm library automatically updates the progress bar in the console as your code runs.Syntax
There are two common ways to create a progress bar in Python:
- Manual progress bar: Use a loop to print characters like hashes (
#) or dots (.) to represent progress. - Using
tqdmlibrary: Wrap your iterable withtqdm()to get a progress bar automatically.
Example syntax for tqdm:
from tqdm import tqdm
for item in tqdm(iterable):
# your code here
python
from tqdm import tqdm for i in tqdm(range(10)): pass
Output
[0%| | 0/10 [00:00<?, ?it/s]
Example
This example shows how to create a simple progress bar manually and then how to use the tqdm library for a nicer progress bar.
python
import time # Manual progress bar print('Manual progress bar:') for i in range(1, 21): print('#' * i + '.' * (20 - i), f' {i*5}%', end='\r', flush=True) time.sleep(0.1) print() # Move to next line # Using tqdm library from tqdm import tqdm print('Progress bar with tqdm:') for i in tqdm(range(20)): time.sleep(0.1)
Output
Manual progress bar:
#################### 100%
Progress bar with tqdm:
100%|████████████████████| 20/20 [00:02<00:00, 9.99it/s]
Common Pitfalls
Common mistakes when creating progress bars include:
- Not flushing the output buffer, so the progress bar does not update smoothly.
- Printing new lines instead of updating the same line, causing cluttered output.
- Forgetting to install or import the
tqdmlibrary before using it.
Always use end='\r' in print() to overwrite the same line for manual bars.
python
import time # Wrong way: prints new lines for i in range(5): print(f'Progress: {i*20}%') time.sleep(0.2) # Right way: overwrite same line for i in range(5): print(f'Progress: {i*20}%', end='\r', flush=True) time.sleep(0.2) print()
Output
Progress: 0%
Progress: 20%
Progress: 40%
Progress: 60%
Progress: 80%
Progress: 100%
Quick Reference
Summary tips for progress bars in Python:
- Use
tqdmfor easy and professional progress bars. - For manual bars, use
print()withend='\r'to update the same line. - Remember to
flush=Trueinprint()if needed for immediate output. - Install
tqdmwithpip install tqdmbefore using it.
Key Takeaways
Use the tqdm library for a simple and effective progress bar in Python.
For manual progress bars, update the same line using print with end='\r'.
Always flush output if progress bar updates are not visible immediately.
Install tqdm with pip before using it in your code.
Avoid printing new lines repeatedly to keep the console clean.