我是Python编码新手,我正在填写一些需要大量输入的代码。它要求的一件事是,如果用户按下回车键并且没有输入任何输入,则程序执行一项操作。我的问题是如何让 python 来检查这一点。会不会是:
if input == "":
#action
还是别的什么?谢谢您的帮助。
编辑:这是我的代码当前的样子,以供参考。
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
我知道这个问题已经很老了,但我仍然分享您问题的解决方案,因为它可能对其他人有帮助。要检测 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"
希望这有帮助。
实际上是一个空字符串
""
而不是
" "
后者是空格字符
编辑
其他一些注意事项
不要使用
input
作为 Python 关键字的变量名比较相等使用
==
而不是=
,后者是一个赋值运算符,它试图修改左侧的值。我是 python 新手,正在寻找类似问题的解决方案。我知道这是一篇非常旧的文章,但我想我应该尝试一下。如果我正确理解你的问题以及你想要实现的目标,这对我来说效果很好。 (只要您不尝试输入字母即可!) 我之前发过帖子,但是不合适,抱歉。
totalcoins = None
coinN = None
sum_total = range
while coinN != '0' and totalcoins != '0':
coinN = input("Please enter first amount: ")
if coinN == "":
print("You didn't enter anything")
else:
totalcoins = input("Please enter second amount ")
if totalcoins == "":
print("You didn't enter anything")
else:
sum_total = int(coinN) + int(totalcoins)
if sum_total in range(100):
print('Sorry, you only entered {} cents'.format(sum_total))
else:
if sum_total == 100:
print('The sum of {0} and {1} is = 1 rand '.format(coinN, totalcoins, sum_total))
if sum_total >=100:
print('The sum of {0} and {1} is = {2} rand '.format(coinN, totalcoins, sum_total))
print("\n")
编辑:
这样的事情怎么样:
try:
coinN = input("Enter next coin: ")
if coinN.isdigit(): # checks whether coinN is a number
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.")
else:
raise ValueError
except ValueError:
print("Invalid Input")
else:
totalcoin = totalcoin + int(coinN) # convert coinN to int for addition
如果您不知道您正在采用的矩阵输入的行数和列数,您可以尝试这个
matrix=[]ok=True
虽然还好: 尝试: l=输入() 如果不是 l 或 l=="": 休息 别的: li=列表(l.split(",")) li=[int(i) for i in li] 矩阵.append(li) 除了 EOF 错误: 好的=假 打破