0

As with the print statement, it's pretty clear that I can access this variable, and I know I cannot modify global variables in a function, but do loops only work for local variables, which seems to be the case. Can anyone please clarify on variable scopes when working with loops in python. I know I can achieve the intended functionality by declaring the variable in function itself, and I know the loop is an infinite loop, I just want to understand why we can't do this (or precisely what more rules are there regarding scopes and namespaces in loops inside function) I couldn't find this.

def racing_result():
    print(race_on)
    while race_on:
        for colour,turtle in turtles.items():
            if turtle.xcor() > 230:
                winner_colour = turtle.pencolor()
                print(winner_colour)
                
            turtle.forward(random.randint(0,10))
    return winner_colour



if usr_bet:
    race_on = True
colour = racing_result()

  • There is the `global` statement that is used to declare such a variable in the given context. In your code, you are using an undefined variable. In some cases though, it would be clearer in the code to pass those kinds of variables in as parameters to the function. I also notice in your code that `turtles` is not defined. You might want to provide more information regarding all the undefined variables in your snippet. – Ben Y Aug 12 '21 at 19:20
  • The basic rule is: If you assign the variable in the function, it's a local variable, unless you have a `global` or `nonlocal` declaration. If you just read the variable, it will search the enclosing scopes, so you can use global variables this way without doing anything special. – Barmar Aug 12 '21 at 19:24

0 Answers0