0

For example:

def main():
    time.sleep(10)
    pass
    main()

How to break this loop by pressing 'q'?

Vyacheslav
  • 77
  • 10
  • Does this answer your question? [detect key press in python?](https://stackoverflow.com/questions/24072790/detect-key-press-in-python) – MoonMist Jan 09 '21 at 12:44
  • @Aggragoth not the same case. All solutions by link for while/for loops. Im my case need to break function. – Vyacheslav Jan 09 '21 at 13:00
  • Is this a rhetorical question or do you actually intend to recursively call a function within itself? Checking if a key is pressed as @Aggragoth suggested will work, you just need to put the if statement somewhere before the `main()` call. In saying that, you will probably run out of memory at some point too because you're recursively calling the same function which would fill up the call stack at some point. – Grizzle Jan 09 '21 at 13:23

1 Answers1

0

Haven't tested it, but i think this should work.

global stop
stop = False

def main():
    time.sleep(10)
    
    if keyboard.is_pressed('q'):
        global stop
        stop = True
        
    if stop:
        return 0
    else:
        main()
    
Eimantas G
  • 437
  • 3
  • 7