Variable stays as False - Python Beginner

Viewed 39

I'll preface by saying that I'm new to Python. I appologize if this should be extremely simple...

I'm working on "Maze" world on reeborg.ca trying to fix a bug where if your sprite starts with no walls around it, it could loop in a circle. I tried to create an init cycle called "init_homing" where it tests to see if the condition of being in a space with no walls surrounding the sprite is true. If it does, it will move and then run the "init_homing" function again until it has a wall adjacent to it. Once it has this adjacent wall, it should change the seek_goal value to True, which should break the "init_homing" function and continue on to the primary part of the program..

The issue is, is that even though it gets to the else statements which should change the value of seek_goal to True, the seek_goal value remains as False

Thank you in advanced:

seek_goal = False
def turn_right():
    turn_left()
    turn_left()
    turn_left()
def turn_around():
    turn_left()
    turn_left()
def init_homing():
    if right_is_clear() and front_is_clear():
        turn_around()
        if right_is_clear() and front_is_clear():
            turn_right()
            move()
        else:
            seek_goal = True
    else:
        seek_goal = True
        
while seek_goal == False:
    init_homing()

while at_goal() == False and seek_goal == True:
    if right_is_clear():
        turn_right()
        move()
    elif front_is_clear():
        move()
    else:
        turn_left()
1 Answers

If you assign to a variable inside of a function, it's treated as a local variable. The seek_goal variable inside init_homing has no relation to the global one at the top of your file, despite seeming to have the same name.

To demand that Python use the global variable instead, use the global keyword.

def init_homing():
    global seek_goal
    if right_is_clear() and front_is_clear():
        turn_around()
        if right_is_clear() and front_is_clear():
            turn_right()
            move()
        else:
            seek_goal = True
    else:
        seek_goal = True
Related