Exit while loop by user hitting ENTER key

12

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

This question is tagged with python while-loop

~ Asked on 2011-08-31 10:07:36

The Best Answer is


18

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")

~ Answered on 2013-07-25 15:39:28


15

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

~ Answered on 2014-03-19 22:19:15


Most Viewed Questions: