Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the return statement in a while loop?

In my program, I have a timer function, it uses a while loop. I want it to return the time past from its start while looping, without stopping the function.

def timer():
    time_ = 0
    while True:
        time.sleep(1)
        time_ += 1
        return time_

But return breaks the loop. I need something like return to start another function if the time is x :

if timer() < 20:    
    # do something
else:
    # do something else
like image 869
Kirill Avatar asked Apr 07 '26 01:04

Kirill


1 Answers

Use yield. It's like return, but can be used in a loop. For more details, see What does the "yield" keyword do?

def timer():
    time_ = 0
    while True:
        time.sleep(1)
        time_ += 1
        yield time_

for i in timer():
    if i < 20:    
        # do something
    else:
        # do something else
like image 54
DSC Avatar answered Apr 10 '26 03:04

DSC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!