Windtalker87 Windtalker87 - 1 year ago 67
Python Question

Python index out of range when missing user user input

I know this is a simple fix--but I can't for the life of me figure out how to fix this 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:


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

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

If the user pushes "return" without putting a value in for move, the game crashes with a "List Index out of range". I don't understand why the "else" isn't catching that in the while loop.

Answer Source

move[0] checks for the first member of the list, and will throw an IndexError if move is an empty, as when the user simply presses enter. You can check that move is true first: if it isn't, the and operator will circumvent the next check.

It seems that you are expecting a user input with one space, causing two members. You should check that len(move) == 2 to ensure this.

Amend as follows:

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

if len(move) == 2 and move[0] == "go":
   # the rest
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download