因此,我从用户那里获取要存储到列表中的输入,并且使用哨兵循环不断要求用户输入数字。出现的问题是,当用户完成输入值后,我使用“停止”结束循环时,出现错误:
ValueError:以 10 为基数的 int() 的文字无效:“停止”
我不知道为什么,如果是因为当输入是整数时,它输入一个字符串来结束 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()
is 'STOP'
.
如果您希望循环在用户输入任何大写版本时终止'stop'
你应该写
while userInput.upper() != "STOP":
....
捕获用户可以输入的其他内容可能是明智的
userIntput = input("")
try:
nums.append(int(userInput))
except ValueError:
# somehow handle what should happen here...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)