3

Michael Dawson says in his book Python Programming (Third Edition, page 14) that if I enter input("\n\nPress the enter key to exit.") when the user presses the Enter key the program will end.

I have tried this several times and it doesn't happen. I have tried using Python 3.1 and 3.3. Help would be appreciated.

user1251007
  • 15,891
  • 14
  • 50
  • 76
user3306860
  • 51
  • 1
  • 1
  • 2
  • Welcome to Stackoverflow. Please show us the code of what you have tried. – user1251007 Feb 14 '14 at 09:58
  • The program ends when there are no more instructions left to execute, the `input()` only serves as a way of delaying that until the user allows it. This makes sense for example if you start a Python program via double-click under Windows - the Python window would disappear as soon as the program ends, making it impossible to read its output, for example. – Tim Pietzcker Feb 14 '14 at 10:09

5 Answers5

3

This is a fairly straightforward concept, do take a look at this example

x = input("Hit Enter to Exit, or Input any other key to continue ")

if not x :
    print("Exiting the Program.")
    exit()

else:
    a = int(input("\nEnter a Number : "))
    b = int(input("Enter another Number : "))
    print("Sum of the two numbers : ", a+b)
1

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.

arocks
  • 2,862
  • 1
  • 12
  • 20
1

I have found that with python3 the following will work for a simple press any key to exit:

\#!/usr/bin/env python3

x = input("Press Any key to exit")
Michael
  • 3,093
  • 7
  • 39
  • 83
XOP
  • 11
  • 1
1

You can use the built-in msvcrt module.

from msvcrt import getch

print("Press any key to exit...")
junk = getch() # Assign to a variable just to suppress output. Blocks until key press.

Note: This only works on Windows. For cross platform usage see https://stackoverflow.com/a/510364/13460650

c-shubh
  • 159
  • 3
  • 7
0

This is programming not magic, you have to capture the enter keystroke somewhere to exit the application. What i mean is input() wait for the user input some data(text) and you get that data from keyboard where the enter key is pressed.

If you do this for example:

def main():
    input("Press enter and exit")

then when you press enter you will exit because under the input() function there is nothing else to execute. Hope you understand.

emcas88
  • 881
  • 6
  • 15