use*_*234 5 python enter input
我是 python 编码的新手,我正在填写一些需要大量输入的代码。它要求的一件事是,如果用户按下回车键并且没有输入任何输入,程序就执行一个操作。我的问题是你如何让 python 来检查。可不可能是:
if input == "":
#action
Run Code Online (Sandbox Code Playgroud)
或者是别的什么?感谢您的帮助。
编辑:这是我的代码目前的样子以供参考。
try:
coinN= int(input("Enter next coin: "))
if coinN == "" and totalcoin == rand:
print("Congratulations. Your calculations were a success.")
if coinN == "" and totalcoin < rand:
print("I'm sorry. You only entered",totalcoin,"cents.")
except ValueError:
print("Invalid Input")
else:
totalcoin = totalcoin + coinN
Run Code Online (Sandbox Code Playgroud)
我知道这个问题很老,但我仍在分享您的问题的解决方案,因为它可能对其他人有所帮助。要检测 Python 中没有输入,您实际上需要检测“文件结尾”错误。这是在没有输入时引起的:
这可以通过以下代码进行检查:
final=[]
while True:
try:
final.append(input()) #Each input given by the user gets appended to the list "final"
except EOFError:
break #When no input is given by the user, control moves to this section as "EOFError or End Of File Error is detected"
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
实际上一个空字符串将是
""
Run Code Online (Sandbox Code Playgroud)
代替
" "
Run Code Online (Sandbox Code Playgroud)
后者是一个空格字符
编辑
其他一些笔记
不要使用inputPython 关键字作为变量名
比较等式使用==代替=,后者是赋值运算符,它试图修改左侧的值。