Python 缺少用户用户输入时索引超出范围

Python index out of range when missing user user input

我知道这是一个简单的修复——但我一辈子都想不出如何修复这个 IndexError。

def show_status():
    print("\nThis is the " + rooms[current_room]["name"])



rooms = { 

        1 : { "name" : "Highway" ,
              "west" : 2 ,
              "east" : 2 ,
              "north": 2 ,
              "south": 2} ,
        2 : { "name" : "Forest" ,
              "west" : 1 ,
              "east" : 1 , 
              "north": 1 ,
              "south": 1} , 
        }

current_room = 1

while True:

    show_status()

    move = input(">> ").lower().split()


    if move[0] == "go":
        if move[1] in rooms[current_room]:
            current_room = rooms[current_room][move[1]]
        else:
             print("you can't go that way!")
    else:
        print("You didn't type anything!")

如果用户按下 "return" 而没有输入移动值,游戏会崩溃并显示 "List Index out of range"。我不明白为什么 "else" 没有在 while 循环中捕捉到它。

move[0] 检查列表的第一个成员,如果 move 为空,将抛出 IndexError,就像用户只需按回车键一样。您可以先检查 move 是否为真:如果不是,则 and 运算符将绕过下一次检查。

您似乎期待一个 space 的用户输入,导致两个成员。您应该检查 len(move) == 2 以确保这一点。

修改如下:

# ...
move = input(">> ").lower().split()

if len(move) == 2 and move[0] == "go":
   # the rest