When I run the code below:
def run():
test = False
def tester():
if not test:
print("test is false")
else:
print("test is true")
test = not test
tester()
run()
I get the error:
local variable 'test' referenced before assignment
I was under the impression that the child function would have access to the parent functions variables. After playing with this code a bit I've found that if I remove the assignment (test = not test
) then everything works fine.
Why does having an assignment in the child function break this code? If I shouldn't have the assignment in the child function, what would be the best way to toggle the test
flag? Should I just return a value from the child function and use that to toggle test
?