首页 > 解决方案 > 如何为输入重复输入

问题描述

我一直在尝试让我的代码重复一个列表,如果它留空,它可以工作,但如果输入在中断中高于 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

标签: python

解决方案


发生的事情是您只捕获 ValueError ,例如字符串或空值。数字 4 不是错误,因为 4 是整数。如果你想处理 ValueError 和 IndexError 你需要这样做:

#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)
        Computer = ComputerList[ComputerChoice_int -1]
    except Exception as e:
        if e.__class__.__name__ == "ValueError":
            print("You can not leave this blank '%s', try again" % (ComputerChoice,))
            print("")
        elif e.__class__.__name__ == "IndexError":
            print("You can not input numbers bigger than {}, try again".format(len(ComputerList)))
            print("")
    else:
        break

推荐阅读