Search code examples
pythonpython-3.xprogress-barpython-3.6tqdm

How can I use tqdm to show the progress of a while loop?


I have seen tqdm used to show progress in for loops, but I was wondering how to do that with while loops. I have some code here to get the percentages of coin flips at any number of flips:

def flipem():
    global flips, completed_flips, heads, tails, head_amount, tail_amount, total_amount
    while completed_flips != flips:
        flip = randint(1, 2)
        if flip == 1:
            head_amount += 1

        elif flip == 2:
            tail_amount += 1

        else:
            pass

        completed_flips += 1
        total_amount += 1


    if completed_flips == flips:
        global head_percentage, tail_percentage
        head_percentage = head_amount / total_amount * 100
        tail_percentage = tail_amount / total_amount * 100

That code essentially takes a user's input and flips a coin that many times, then gives the percentages of heads and tails.

While this is happening I would like there to be a progress bar but I can't figure out how to use tqdm with a while loop.

Anybody know how or have an alternative? Thanks.

EDIT: Btw, there is more to this code but I decided not to add it because I think it is irrelevant.


Solution

  • As @r.ook said: How does one determine the progress of an infinite loop? It either is looping, or isn't. i.e. 0% or 100%.

    SO, tqdm only works with for loops.

    The solution:

    for i in tqdm(range(flips)):
    

    This way, even without knowing the number of iterations beforehand, it will still show a progress bar.