嵌套ifs中的Indexerror使用python

时间:2012-12-05 18:00:51

标签: python if-statement indexing

运行我正在用乌龟图形绘制的程序,我输入了一个退出命令,但是现在每当我输入任何单字命令时,我在elif处得到一个indexerror(IndexError:list index超出范围) “后退”命令:

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)

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

2 个答案:

答案 0 :(得分: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"):

答案 1 :(得分:0)

elif应该是:

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

您当前的版本被解释为

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

始终评估为True,因为bool("backward")True