3

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
Kirill
  • 303
  • 3
  • 18
  • create a boolean `check = False` then `while True: ..... check = some condition` and finally `if check: do something else: do something else` – Bargros Jun 12 '19 at 13:25
  • Possible duplicate of [Python - How to use a return statement in a for loop?](https://stackoverflow.com/questions/44564414/python-how-to-use-a-return-statement-in-a-for-loop) – wjandrea Jun 12 '19 at 13:54

2 Answers2

3

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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
DSC
  • 1,153
  • 7
  • 21
0

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    
oygen
  • 467
  • 1
  • 7
  • 13