因此,我正在从用户那里获取要存储到列表中的输入,并且我正在使用哨兵循环不断要求用户输入数字。出现的问题是当用户完成输入值时我使用“停止”结束循环时我得到一个错误
ValueError:以 10 为底的 int() 的无效文字:'Stop'
我不确定为什么,如果是因为当输入是整数时它正在输入一个字符串来结束 while 循环。非常感谢任何消除此错误的建议,我的代码也在下面。
def getInput():
nums = []
print("Enter a value, to end the list, input Stop")
userInput = input("")
while userInput.upper() != "Stop":
print("Enter a value, to end the list, input Stop")
nums.append(int(userInput))
userInput = input("")
return nums
def main():
numbers = getInput()
print(numbers)
main()
请您参考如下方法:
userInput.upper() != "Stop":
将始终为 True:'stop'.upper() 为 'STOP'。
如果你希望你的循环在用户输入任何大写版本的'stop'时终止,你应该这样写
while userInput.upper() != "STOP":
....
并且捕获用户可以输入的其他内容可能是明智的
userIntput = input("")
try:
nums.append(int(userInput))
except ValueError:
# somehow handle what should happen here...
