如何修正无效的边界输入

时间:2018-08-09 06:00:29

标签: python

我添加了

Length = len(gamelist) 

在我的代码中进行了更改,并进行了一些其他更改,以便在添加了额外的游戏后,所有内容都会自动更改,但我认为这样做的话,在第一个问题中输入4时的边界值就是“您想要什么数字游戏?它会显示一条错误消息:

Traceback (most recent call last):
  File "/Users/megan/Desktop/Digital/Python/m2.py", line 28, in <module>
    print ("You have chosen",gamelist[gamenum],)
IndexError: list index out of range

我想知道是否有任何方法可以解决此问题,所以当我输入4时,它只是说这是无效的输入。我需要保持我的代码相对相似,并且需要拥有'LENGTH = len(gamelist)',我知道它很杂乱,但是我需要保持相同。一切都会有帮助的。

我使用的代码是:

#Ask user what game they would like to play
def game () :
    global gametype,gamelist
    gamelist = ["Mario Cart","Minecraft","Angry Birds","Grand Theft Auto"]
    gamecount = 0
    LENGTH = len(gamelist)
    print ("Hello the four games avaliable are:")

    while gamecount < LENGTH:
        print (gamecount," ",gamelist[gamecount])
        gamecount = gamecount + 1

#Makes sure program runs if input invalid       
    while True:
        try:
            gamenum = int(input("What number game do you want? "))
            if 0 <= gamenum < LENGTH:
                gametype = gamenum
                return gamenum
            print ("Please enter a number between 0 and",gamecount - 1)
            print ("")

        except ValueError:
                print ("Please enter a valid value from 0 to",gamecount - 1)
                print ("")

gamenum = game ()
print ("You have chosen",gamelist[gamenum],)
print ("")

#Ask game level
def number():
    while True:
        try:
            Level = int(input("What is the level you would like to play at? "))

            if Level <= 1 and Level <= 25:
                print ("Beginner ")
                return ("Beginner")

            elif Level >=26 and Level <=75:
                print ("Intermediate")
                return ("Intermediate")

            elif Level >=76 and Level <=100:
                print ("Advanced")
                return ("Advanced")

#Makes sure program runs if input invalid
            else:
                print("Out Of range (1-100): Please enter a valid number")
                print ("")

        except ValueError:
            print("Please enter a valid number")
            print ("")


#Create a subroutine to print out the action message
def printmessage ():
    global gametype, num
    print ("")
    print ("#                                                      #")
    print ("########################################################")
    print ("#################### ACTION MESSAGE ####################")
    print ("########################################################")
    print ("#                                                      #")
    print ("Play "+gamelist[gametype]+" at "+num)
    print ("#                                                      #")
    print ("########################################################")
    print ("#################### ACTION MESSAGE ####################")
    print ("########################################################")
    print ("#                                                      #")

#This is to let the program work
def main ():
    global num
    num = number()

    printmessage ()

main()

3 个答案:

答案 0 :(得分:0)

您的try: ... except:语句未捕获无效的gamenum

if 0 <= gamenum <= len(gamelist):之后尝试添加

else:
    raise ValueError

答案 1 :(得分:0)

编辑:很明显,在我写下答案后,问题已被编辑,并且该错误已修复。

您可能在代码中遇到问题,包括全局变量和命名约定,但是我将尝试仅解决与异常相关的部分。在print行触发了异常:

gamenum = game ()
print ("You have chosen",gamelist[gamenum],)

这意味着game()返回了越界索引。因此,让我们看一下game()的相关部分:

gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= LENGTH:
     gametype = gamenum
     return gamenum

错误就在那里。像所有最流行的编程语言一样,Python中的列表被零索引了。这意味着:

gamelist = ["Mario Cart","Minecraft","Angry Birds","Grand Theft Auto"]

您得到:

gamelist[0] == "Mario Cart"
gamelist[1] == "Minecraft"
gamelist[2] == "Angry Birds"
gamelist[3] == "Grand Theft Auto"

然后gamelist[4]将引发IndexError。这意味着您需要停止从game()返回gamenum == 4

gamenum = int(input("What number game do you want? "))
if 0 <= gamenum < LENGTH:
     gametype = gamenum
     return gamenum

答案 2 :(得分:0)

例外ValueError: 当操作或函数接收到类型正确但值不合适的参数时引发,并且这种情况没有通过更精确的异常(如IndexError)描述。

您有

gamenum = int(input("What number game do you want? "))

例如,如果用户输入符号或unicode,则可能发生异常

如果用户输入非数字的有效字符,则强制转换为int也会发生异常。

如果用户输入有效的字符串(例如999),则不会发生异常。

So you need to do the range check yourself