如何知道用户是否使用 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
How to know if a user has pressed the Enter key using 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 input
function 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 input
function would throw an exception such as:
我看到的退出input
函数的唯一其他方法会引发异常,例如:
EOFError
if you type^D
KeyboardInterrupt
if 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.
'''