0

运行我正在使用海龟图形绘制的程序,我输入了一个退出命令,但是现在每当我输入任何单字命令时,我都会在“返回”的 elif 处得到一个 indexerror(IndexError:list index out of range)命令:

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)

为什么?我该如何解决这个问题?

4

2 回答 2

1
elif items_in_line[0] == "back" or "backward":

上述条件相当于:-

elif (items_in_line[0] == "back") or "backward":

它将始终被评估为 true,因此如果您将“exit”作为输入传递也将被执行,因此items_in_line[1]将抛出IndexError.

您需要将条件更改为: -

elif items_in_line[0] in ("back", "backward"):
于 2012-12-05T18:04:53.397 回答
0

elif应该是:

elif items_in_line[0] in ("back", "backward"):

您当前的版本被解释为

elif (items_in_line[0] == "back") or bool("backward"):

总是评估为True,因为bool("backward")True

于 2012-12-05T18:04:53.147 回答