Jul-03-2019, 02:25 PM
To add to what perfringo said, note that Python looks ahead for assignments:
It is indeed a subtle and twisty topic.
>>> def foo(): ... print(x) ... x = 3 ... return x + 5 ... >>> x = 5 >>> foo() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in foo UnboundLocalError: local variable 'x' referenced before assignmentPython saw that you were going to assign to x in the function, so it decided was in local scope. Then it processed the print call, and couldn't find x in the local scope, and didn't bother to check the further scopes as it otherwise would. If you didn't have the assignment, it would work just like prefringo says.
It is indeed a subtle and twisty topic.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures