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

缺少用户输入时Python索引超出范围,python,indexoutofrangeexception,Python,Indexoutofrangeexception,我知道这是一个简单的修复方法——但我一辈子都不知道如何修复这个索引器 def show_status(): print("\nThis is the " + rooms[current_room]["name"]) rooms = { 1 : { "name" : "Highway" , "west" : 2 , "east" : 2 , "north": 2 ,

我知道这是一个简单的修复方法——但我一辈子都不知道如何修复这个索引器

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”,游戏将崩溃,出现“列表索引超出范围”。我不明白为什么“else”在while循环中没有捕捉到这一点

move[0]
检查列表的第一个成员,如果
move
为空,则会抛出一个
索引器,就像用户只需按enter键一样。您可以先检查
move
是否为真:如果不是,则
操作符将绕过下一个检查

似乎您希望用户输入一个空格,导致两个成员。您应该检查
len(move)==2以确保这一点

修正如下:

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

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

崩溃发生在
else
之前:例如,您需要检查move和move[0]==“go”
。问题是当它有零个元素时,试图访问
移动[0]
。你们太棒了。非常感谢。回到做一个很棒的文字冒险。