0

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?

1
  • 1
    Note that changing the last else to elif as you did will also not solve the issue. As the check will not reach it. You need to change the 2nd elif. Commented Dec 5, 2012 at 18:10

2 Answers 2

1
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"):
Sign up to request clarification or add additional context in comments.

1 Comment

@user1879595. See my comment on your change. It will not solve your issue by change the last else to elif.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.