我在for循环内的嵌套if elif语句的elif部分出现错误

时间:2019-04-10 03:23:52

标签: python-3.x

我收到无效的语法错误:

Language detected: python
Traceback (most recent call last):
  File "Labs/Lab1/src/main.py", line 2, in <module>
    import student_code
  File "/Users/dhanvin/Desktop/py/EECS348_Labs/Labs/Lab1/src/student_code.py", line 32
    elif "left":
       ^
SyntaxError: invalid syntax

我尝试删除了if和elifs之间的空行

def fillChildren(loc):
    direction = ("right", "down", "left", "up")
    for i in direction:
        if "right":
            if loc[1] == common.constants.MAP_WIDTH-1 or map[loc[0]][loc[1]+1] != 0:
                continue
            child = ((loc[0], loc[1]+1))
        elif "down":
            if loc[0] == common.constants.MAP_HEIGHT-1 or map[loc[0]+1][loc[1]] != 0:
                continue
            child.append((loc[0]+1, loc[1])
        elif "left":
            if loc[1] == 0 or map[loc[0]][loc[1]-1] != 0:
                continue
            child.append((loc[0], loc[1]-1))
        elif "up":
            if loc[0] == 0 or map[loc[0]-1][loc[1]] != 0:
                continue
            child.append((loc[0]-1, loc[1]))

    return child

1 个答案:

答案 0 :(得分:0)

您忘记将变量添加到条件语句中,例如if i == left,因此代码应类似于

def fillChildren(loc):
    direction = ("right", "down", "left", "up")
    child = None
    for i in direction:
        if i == "right":
            if loc[1] == common.constants.MAP_WIDTH-1 or map[loc[0]][loc[1]+1] != 0:
                continue
            child = (loc[0], loc[1]+1)
        elif i == "down":
            if loc[0] == common.constants.MAP_HEIGHT-1 or map[loc[0]+1][loc[1]] != 0:
                continue
            child.append((loc[0]+1, loc[1]))
        elif i == "left":
            if loc[1] == 0 or map[loc[0]][loc[1]-1] != 0:
                continue
            child.append((loc[0], loc[1]-1))
        elif i == "up":
            if loc[0] == 0 or map[loc[0]-1][loc[1]] != 0:
                continue
            child.append((loc[0]-1, loc[1]))

    return child