There must be an easier way to interrupt loops! Or do I really have to use multi threading? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

There must be an easier way to interrupt loops! Or do I really have to use multi threading?

Could you please show me what I would need to add, so when a key is pressed, the infinte while loop stops but it still prints 'Finished'? while(True): print('Hello') print('Finished') Of course I could simply close the Window, or press ctrl+c, but then it would not print 'Finished' any more. I'd prefer to send an interrupt from the keyboard, which allows me to close only the infinite loop. While the following commands are still executed. I thougt about using multi threading, the actual thread which would normally be executed infinitely, and another which gets the input and tells the other thread to stop. But it has to be way more easier, doesn't it?

19th Oct 2016, 7:16 PM
Julian
2 Answers
+ 5
From Keith at stackoverflow.com: try: while True: print('Hello') except KeyboardInterrupt: pass print('Finished') Then use Ctrl+C.
19th Oct 2016, 7:58 PM
Zen
Zen - avatar
+ 1
Nice solution.
1st Nov 2016, 4:28 PM
Kirk Schafer
Kirk Schafer - avatar