如何知道用户是否使用 Python 按下了 Enter 键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23979184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:46:04  来源:igfitidea点击:

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

python

提问by user116284

How to know if a user has pressed Enterusing Python ?

如何知道用户是否按下了EnterPython ?

For example :

例如 :

user = raw_input("type in enter")
if user == "enter":
    print "you pressed enter"
else:
    print "you haven't pressed enter"

回答by julienc

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

正如@jonrsharpe 所说,正确退出该input功能的唯一方法是按 Enter。因此,解决方案是检查结果是否包含某些内容:

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 inputfunction would throw an exception such as:

我看到的退出input函数的唯一其他方法会引发异常,例如:

  • EOFErrorif you type ^D
  • KeyboardInterruptif you type ^C
  • ...
  • EOFError如果你输入 ^D
  • KeyboardInterrupt如果你输入 ^C
  • ...

回答by MIGHTY BOMBER

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