Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"
like image 590
chaudim Avatar asked Jun 01 '14 11:06

chaudim


1 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
  • ...
like image 74
julienc Avatar answered Oct 15 '22 06:10

julienc