我一直在尝试让我的代码对列表进行重复,如果将其留空则可以工作,但如果输入在中断中大于4,我仍在尝试掌握python的诀窍
我试着为这个问题找到一个解决方案,但不知道该怎么做
#Create a list for when they select the computer they want
ComputerList = ["(1)Home Basic $900", "(2)Office $1200", "(3)Gamer $1500", "(4)Studio $2200"]
#Ask them what they want and repeat if left blank
while True:
ComputerChoice = input("What computer would you like to buy?(Use the number beside it 1-4): ")
print("")
try:
ComputerChoice_int = int(ComputerChoice)
except ValueError:
print("You can not leave this blank '%s', try again" % (ComputerChoice,))
print("")
else:
break
我希望它会重复,但它想出了
Traceback (most recent call last):
File "\\hnhs-fs01\StudentUsers$\17031\Documents\11 DTG\1.7\Assement\Assessment computer.py", line 69, in <module>
Computer = ComputerList[ComputerChoice_int -1]
IndexError: list index out of range
发布于 2019-06-06 07:23:24
问题出在哪里?这段代码运行得很好。
#Create a list for when they select the computer they want
ComputerList = ["(1)Home Basic $900", "(2)Office $1200", "(3)Gamer $1500", "(4)Studio $2200", "test (5)"]
#Ask them what they want and repeat if left blank
while True:
print(ComputerList)
ComputerChoice = input("What computer would you like to buy?(Use the number beside it 1-%s): " % len(ComputerList))
try:
ComputerChoice_int = int(ComputerChoice) - 1
if not -1 < ComputerChoice_int < len(ComputerList):
raise ValueError
print("ok")
break
except ValueError:
print("Something went bad :/\n")
发布于 2019-06-06 07:24:40
你可以这样做,使用int(input())
会让一切变得更好+你不需要排除错误。
ComputerList = ["(1)Home Basic $900", "(2)Office $1200", "(3)Gamer $1500", "(4)Studio $2200"]
while True:
ComputerChoice = int(input("What computer would you like to buy?(Use the number beside it 1-4): "))
if ComputerChoice not in range(1,5):
print("invalid input")
else:
print("You selected {}".format(ComputerList[ComputerChoice-1]))
# Do whatever here
发布于 2019-06-06 07:28:52
它崩溃是因为你没有捕获大于4的输入的子句。它只会在字段不能转换为整数的情况下引发错误。现在您可以硬编码4 in,但更可靠的方法是使用列表的长度。如果您添加或删除计算机,这将使您的代码更容易更新。
这就是我要做的:
ComputerList = ["(1)Home Basic $900", "(2)Office $1200", "(3)Gamer $1500", "(4)Studio $2200"]
max_integer = len(ComputerList)
status = False
while status == False:
try:
Choice = int(input("enter your choice"))
if 0 < Choice <= max_integer:
status = True
except ValueError:
print('input is invalid')
pass
这是可以缩短的,但我把它画了一点,这样你就能明白发生了什么。
https://stackoverflow.com/questions/56469068
复制相似问题