Kirill
Kirill

Reputation: 313

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

Upvotes: 3

Views: 361

Answers (2)

DSC
DSC

Reputation: 1153

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

Upvotes: 3

oygen
oygen

Reputation: 507

you reset time_ = 0 every time you call timer() function.

Try to instantiate time_ outside of the function so it can keep incrementing next time you call timer()function.

time_ = 0

def timer ():
    time_ += 1
    return time    

Upvotes: 0

Related Questions