I am a python newbie and have been asked to carry out some exercises using while and for loops. I have been asked to make a program loop until exit is requested by the user hitting <Return>
only. So far I have:
User = raw_input('Enter <Carriage return> only to exit: ')
running = 1
while running == 1:
Run my program
if User == # Not sure what to put here
Break
else
running == 1
I have tried: (as instructed in the exercise)
if User == <Carriage return>
and also
if User == <Return>
but this only results in invalid syntax. Please could you advise me on how to do this in the simplest way possible. Thanks
Use KeyboardInterrupt to kill a while loop with a keystroke Use a try except statement with the while loop inside of the try block and a Keyboard Interrupt exception in the except statement. When Ctrl-C is pressed on the keyboard, the while loop will terminate.
The input() function merely waits for you to enter a line of text (optional) till you press Enter. The sys. exit("some error message") is the correct way to terminate a program. This could be after the line with the input() function.
Imagine the code in your loop takes 20 seconds to process and is called at 9.9 seconds. Your code would exit after 29.9 seconds of execution. If you want to exactly stop after 10 seconds, you have to execute your code in an external thread that you will kill after a certain timeout.
To end a while loop prematurely in Python, press CTRL-C while your program is stuck in the loop. This will raise a KeyboardInterrupt error that terminates the whole program. To avoid termination, enclose the while loop in a try/except block and catch the KeyboardInterrupt .
I ran into this page while (no pun) looking for something else. Here is what I use:
while True:
i = input("Enter text (or Enter to quit): ")
if not i:
break
print("Your input:", i)
print("While loop has exited")
The exact thing you want ;)
https://stackoverflow.com/a/22391379/3394391
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
break
i += 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With