Exit while loop by user hitting ENTER key
Asked Answered
B

15

13

I am a python newbie and have been asked to carry out an exercise: 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

I have tried: (as instructed in the exercise)

if User == <Carriage return>

and also

if User == <Return>

but this only results in invalid syntax.

How do I do this in the simplest way possible?

Barmen answered 31/8, 2011 at 10:7 Comment(0)
J
22

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")
Juvenility answered 25/7, 2013 at 15:39 Comment(2)
Simple, effective, and pythonic.Averse
Raises SyntaxError: unexpected EOF while parsing in Python 2. Using raw_input may fix, but I haven't tried it.Monkeypot
P
17

The exact thing you want ;)

from answer by limasxgoesto0 on "Exiting while loop by pressing enter without blocking. How can I improve this method?"

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
Pull answered 19/3, 2014 at 22:19 Comment(2)
This is an excellent answer. Here is (I believe) the original source, which has further information about non-blocking stdin: repolinux.wordpress.com/2012/10/09/…Newfoundland
os.system('cls' if os.name == 'nt' else 'clear') is not relevant to the questionAmling
T
5

Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.

  1. If you use raw_input() in python 2.7 or input() in python 3.0, The program waits for the user to press a key.
  2. If you don't want the program to wait for the user to press a key but still want to run the code, then you got to do a little more complex thing where you need to use kbhit() function in msvcrt module.

Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link

I think the following links would also help you to understand in much better way.

  1. python cross platform listening for keypresses

  2. How do I get a single keypress at a time

  3. Useful routines from the MS VC++ runtime

I hope this helps you to get your job done.

Tacklind answered 30/1, 2012 at 14:29 Comment(0)
W
2

This works for python 3.5 using parallel threading. You could easily adapt this to be sensitive to only a specific keystroke.

import time
import threading


# set global variable flag
flag = 1

def normal():
    global flag
    while flag==1:
        print('normal stuff')
        time.sleep(2)
        if flag==False:
            print('The while loop is now closing')

def get_input():
    global flag
    keystrk=input('Press a key \n')
    # thread doesn't continue until key is pressed
    print('You pressed: ', keystrk)
    flag=False
    print('flag is now:', flag)

n=threading.Thread(target=normal)
i=threading.Thread(target=get_input)
n.start()
i.start()
Walz answered 28/11, 2017 at 20:40 Comment(1)
Some very minor nitpicking: flag = 1 -> flag = True. while flag==1 -> while flag. if flag==False: -> if not flag:. And you only have to state the global if you want to write to a variable, so you can remove global flag from normal().Camshaft
O
1

Use a print statement to see what raw_input returns when you hit enter. Then change your test to compare to that.

Orvah answered 31/8, 2011 at 10:12 Comment(3)
the print statement is blank so I have tried User == '' but still this line is highlighted as invalid syntaxBarmen
raw_input will not capture <enter> or <return>Obscurant
You forgot repr(). Otherwise printing doesn't show anything. print(repr(User))Amling
Y
0

You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)

Yasmeen answered 31/8, 2011 at 10:13 Comment(2)
I tried to use a print statement to do this and the variable is blank so I tried User == '' but this results in invalid syntax as does User == '\n'Barmen
Why should you be doing User == "? " is invalid Syntax. I'll help you even a bit more (even though this is soooo obvious actually): print repr(raw_input()) and just hit enter.Yasmeen
C
0

Here's a solution (resembling the original) that works:

User = raw_input('Enter <Carriage return> only to exit: ')
while True:
    #Run my program
    print 'In the loop, User=%r' % (User, )

    # Check if the user asked to terminate the loop.
    if User == '':
        break

    # Give the user another chance to exit.
    User = raw_input('Enter <Carriage return> only to exit: ')

Note that the code in the original question has several issues:

  1. The if/else is outside the while loop, so the loop will run forever.
  2. The else is missing a colon.
  3. In the else clause, there's a double-equal instead of equal. This doesn't perform an assignment, it is a useless comparison expression.
  4. It doesn't need the running variable, since the if clause performs a break.
Confluence answered 26/9, 2012 at 21:1 Comment(1)
It's better to use only one input statement. See this answer under "The Redundant Use of Redundant input Statements"Amling
P
0
user_input = input("ENTER SOME POSITIVE INTEGER : ")
if (not user_input) or (int(user_input) <= 0):
   print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO")  # print some info
   import sys  # import
   sys.exit(0)  # exit program

not user_input checks if user has pressed enter key without entering number.

int(user_input) <= 0 checks if user has entered any number less than or equal to zero.

Picky answered 30/7, 2015 at 21:18 Comment(1)
You need to provide some discussion explaining how your answer addresses the question.Anderson
S
0

You are nearly there. the easiest way to get this done would be to search for an empty variable, which is what you get when pressing enter at an input request. My code below is 3.5

running = 1
while running == 1:

    user = input(str('Enter <Carriage return> only to exit: '))

    if user == '':
        running = 0
    else:
        print('You had one job...')
Salute answered 27/11, 2016 at 19:9 Comment(0)
E
0

I recommend to use u\000D. It is the CR in unicode.

Ejectment answered 10/12, 2022 at 12:15 Comment(1)
I edited your post to reduce the impression that you only want to comment. If you indeed want to comment instead of actually answering please delete this and wait for your commenting privilege. meta.stackexchange.com/questions/214173/…Rolanderolando
T
-1
if repr(User) == repr(''):
    break
Toul answered 31/8, 2011 at 10:16 Comment(2)
this line is still being highlighted as invalid syntaxBarmen
repr? Why? You can just do User == ''...Amling
D
-1

a very simple solution would be, and I see you have said that you would like to see the simplest solution possible. A prompt for the user to continue after halting a loop Etc.

raw_input("Press<enter> to continue")
Disputation answered 5/3, 2015 at 21:49 Comment(0)
M
-1

Here is the best and simplest answer. Use try and except calls.

x = randint(1,9)
guess = -1

print "Guess the number below 10:"
while guess != x:
    try:
        guess = int(raw_input("Guess: "))

        if guess < x:
            print "Guess higher."
        elif guess > x:
            print "Guess lower."
        else:
            print "Correct."
    except:
        print "You did not put any number."
Mouthful answered 1/5, 2016 at 6:58 Comment(1)
A bare except is bad practice. Instead, use the specific exception you're expecting like except ValueError for invalid int strings, or at least except Exception, which would also include KeyboardInterrupt and EOFError.Amling
S
-2

If you want your user to press enter, then the raw_input() will return "", so compare the User with "":

User = raw_input('Press enter to exit...')
running = 1
while running == 1:
    ...  # Run your program
    if User == "":
        break
Strangles answered 31/8, 2011 at 10:15 Comment(2)
I have attempted this but the 5th line is still highlighted as invalid syntaxBarmen
You also need a : after the else, and running == 1 is a boolean expression not an assignment.Burget
R
-3

The following works from me:

i = '0'
while len(i) != 0:
    i = list(map(int, input(),split()))
Rancidity answered 9/11, 2017 at 1:56 Comment(1)
Please explain your code, and what more does it bring that other answers do not.Salomie

© 2022 - 2024 — McMap. All rights reserved.