1. while loop
Python's while
loop can print a progress bar, which can be tqdm
achieved using this library. tqdm
is a library for adding progress bars in Python, which can be easily integrated into while
loops.
Here's a simple example that uses while
a loop and tqdm
library to print a progress bar from 1 to 100:
from tqdm import tqdm
i = 0
pbar = tqdm(total=100)
while i < 100:
i += 1
pbar.update(1)
pbar.set_description("Processing %d" % i)
# 执行循环体内的代码
pbar.close()
In the above code, first tqdm
the library is imported. Then, use a variable i
to count the number of loop iterations. An object is also created tqdm
and its total
parameter set to 100 so it knows the total number of times it needs to iterate.
On each loop iteration, increment i
the value of 1 and then increment the progress bar's value by calling tqdm
the object's method. update()
We also set the progress bar's description by calling a method tqdm
on the object set_description()
so that it will display the number currently being processed.
Finally, at the end of the loop, tqdm
the object is closed to ensure the progress bar is displayed correctly.
It is important to note that in order to use tqdm
the library, you need to first pip
install it via . You can install it in terminal with tqdm
:
pip install tqdm
2. for loop
It is relatively simple to implement
for i in tqdm(range(10)):# 显示进度条