Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit while loop by user hitting ENTER key

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

like image 829
Candace Avatar asked Aug 31 '11 10:08

Candace


People also ask

How do you break a while loop with a key press?

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.

How do you press Enter to exit in Python?

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.

How do you exit a while loop after a certain time?

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.

How do you stop a loop when a key is pressed Python?

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 .


2 Answers

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")
like image 103
ptay Avatar answered Sep 22 '22 01:09

ptay


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
like image 32
user3394391 Avatar answered Sep 23 '22 01:09

user3394391