Reputation: 418
running a program I am making to draw with turtle graphics, I put in an exit command, however now whenever I enter any single-word commands I get an indexerror (IndexError: list index out of range) at the elif for the "back" command:
def parse_line(line):
global items_in_line
items_in_line = line.split(" ",1)
if items_in_line[0] == "forward":
if isinstance(items_in_line[1], int):
return items_in_line
elif items_in_line[0] == "back" or "backward":
if isinstance(items_in_line[1], int):
return items_in_line
...
elif items_in_line[0] == "exit":
sys.exit()
line=input("Enter a turtle command or enter 'file' to load commands from a file")
x = parse_line(line)
Why? and how can I fix this?
Upvotes: 0
Views: 116
Reputation: 213311
elif items_in_line[0] == "back" or "backward":
the above condition is equivalent to: -
elif (items_in_line[0] == "back") or "backward":
Which will always be evaluated to true, and thus will also be executed if you pass "exit" as input, and hence items_in_line[1]
will throw IndexError
.
You need to change the condition to: -
elif items_in_line[0] in ("back", "backward"):
Upvotes: 1
Reputation: 500585
That elif
should read:
elif items_in_line[0] in ("back", "backward"):
Your current version is interpreted as
elif (items_in_line[0] == "back") or bool("backward"):
which always evaluates to True
, since bool("backward")
is True
.
Upvotes: 0