python(9):python loop print progress bar

1. while loop

Python's whileloop can print a progress bar, which can be tqdmachieved using this library. tqdmis a library for adding progress bars in Python, which can be easily integrated into whileloops.

Here's a simple example that uses whilea loop and tqdmlibrary 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 tqdmthe library is imported. Then, use a variable ito count the number of loop iterations. An object is also created tqdmand its totalparameter set to 100 so it knows the total number of times it needs to iterate.

On each loop iteration, increment ithe value of 1 and then increment the progress bar's value by calling tqdmthe object's method. update()We also set the progress bar's description by calling a method tqdmon the object set_description()so that it will display the number currently being processed.

Finally, at the end of the loop, tqdmthe object is closed to ensure the progress bar is displayed correctly.

It is important to note that in order to use tqdmthe library, you need to first pipinstall 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)):# 显示进度条

Guess you like

Origin blog.csdn.net/BIT_HXZ/article/details/130460545