Home > Net >  Elif syntax error with nested if conditions
Elif syntax error with nested if conditions

Time:11-30

The interpreter gives me a syntax error when it reaches elif in the code below. Why?

while walls:
    rand_wall = walls[int(random.random()*len(walls))-1]
    if rand_wall[1] != 0 and rand_wall[1] != mazeheight-1:
        if maze[rand_wall[0][rand_wall[1]-1] == "u" and maze[rand_wall[0][rand_wall[1] 1] == "c":
            print("no")
        elif maze[rand_wall[0][rand_wall[1]-1] == "c" and maze[rand_wall[0][rand_wall[1] 1] == "u":
            print("no")

If the first condition is true, I want to check a second condition and its mirror condition and run some code (replaced with print("no") for debugging) if either condition is true.

CodePudding user response:

There are some closing brackets missing.

while walls:
    rand_wall = walls[int(random.random()*len(walls))-1]
    if rand_wall[1] != 0 and rand_wall[1] != mazeheight-1:
        if maze[rand_wall[0][rand_wall[1]-1] == "u" and maze[rand_wall[0][rand_wall[1] 1]]] == "c": # added two closing brackets before the == sign.
            print("no")
        elif maze[rand_wall[0][rand_wall[1]-1] == "c" and maze[rand_wall[0][rand_wall[1] 1]]] == "u": # same as before
            print("no")

It should run now, but I don't know the expected behavior. Next time try to post the full stack trace.

CodePudding user response:

I would clean this up to avoid the chance of syntax error. I'm assuming, for example, that

maze[rand_wall[0][rand_wall[1]-1]

should be

maze[rand_wall[0]][rand_wall[1]-1] 
                 ^
                 add missing ]

while walls:
    x, y = random.choice(walls)
    if y != 0 and y != mazeheight-1:
        row = maze[x]
        if row[y-1] == "u" and row[y 1] == "c":
            print("no")
        elif row[y-1] == "c" and row[y 1] == "u":
            print("no")
  • Related