How to know if a user has pressed the Enter key using Python

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

3 Answers

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
  • ...
2

You have to install a package called getkey

from getkey import getkey, key print("press enter") var = getkey() if var == key.ENTER: print("You pressed enter") else: print("You didnt") 

It will only take a one character input though

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. ''' 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like