14

How to know if a user has pressed Enter using Python ?

For example :

user = raw_input("type in enter")
if user == "enter":
    print "you pressed enter"
else:
    print "you haven't pressed enter"
jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
chaudim
  • 383
  • 1
  • 3
  • 15
  • 5
    Well if they don't press Enter `raw_input` won't return, so the check seems redundant. What are you trying to achieve? Could you review your syntax and formatting, please? As it stands, that isn't python. – jonrsharpe Jun 01 '14 at 11:05
  • Hi, sorry i'm a student still at the beginning of the programming learning curve. My task is to create a program which will execute a task only if the user presses the enter key. Also Could you elaborate on whats wrong with the formatting and syntax. – chaudim Jun 01 '14 at 12:00
  • julienc has fixed the formatting and syntax for you - you were missing a colon and using `=` (assignment) instead of `==` (comparison). `raw_input` will wait until the Enter key is pressed, so is not appropriate for what you are trying to do. Also, `"enter"` is a series of characters, *not* the Enter key. – jonrsharpe Jun 01 '14 at 12:07
  • You should use \n as enter. It means the newline character. – les Aug 06 '15 at 10:12

2 Answers2

27

As @jonrsharpe said, the only way to exit properly the input function is by pressing enter. So a solution would be to check if the result contains something or not:

text = input("type in enter")  # or raw_input in python2
if text == "":
    print("you pressed enter")
else:
    print("you typed some text before pressing enter")

The only other ways I see to quit the input function would throw an exception such as:

  • EOFError if you type ^D
  • KeyboardInterrupt if you type ^C
  • ...
julienc
  • 15,239
  • 15
  • 74
  • 77
  • For Python 3.xx, `input` must be used instead of `raw_input`. – jeppoo1 Mar 06 '20 at 10:16
  • 2
    @jeppoo1 you're right, I wrote this back in 2014, when python2 was still a thing :) I've just updated my answer to comply with python3 though! – julienc Mar 06 '20 at 10:19
-2
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.
'''