While libraries like tqdm are fantastic, sometimes you just need a quick and simple progress bar for a long-running loop without adding another dependency.
Here’s the complete code snippet:
# 'i' is the loop index and 'total' is the number of items
percent = (i + 1) / total
chars = int(percent * 50) # filled chars count
print(f"Task [{'':=^{chars}}>{'':.^{50-chars}}] {percent*100:.0f} % ",
end="\r", flush=True)
This tiny block of code produces a clean, updating progress bar right in your terminal:
Task [==================>...............................] 36 %
The beauty of this solution lies in its simplicity and portability. It uses only built-in Python features, making it trivial to drop into any script. The core technique is also easily adaptable to other languages like C or Java using their respective formatted printing functions.
How It Works
Let’s demystify this “magic” by examining each line.
- Calculate the Percentage: We compute the completion percentage using
(i + 1) / total. The +1 ensures we count from 1% to 100% rather than 0% to 99%. - Visual Fill: We determine how many
=characters to display by scaling the percentage to our 51-character bar width. - The Formatting Magic: This line is the heart of the operation, combining powerful f-string formatting with two special arguments for the
print()function.
The syntax{'':=^{chars}}is a clever trick. It tells Python to create a string of lengthcharsand fill it with the=character. Similarly,{'':.^{50-chars}}creates the “empty” part of the bar using.characters. The>is just a character we use to show the current position.flush=Trueensures immediate output for smooth animation, whileend='\r'returns the cursor to the line start for seamless updates.