#π Global scope and UnboundLocalError
22 messages Β· Page 1 of 1 (latest)
@primal gazelle
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
What is the OUTPUT generated by this code?
x = 6
def f():
print("Within f: x =", x)
x = 12
print("Within f: x =", x)
print("Before f: x =", x)
f()
print("After f: x =", x)
a.
an error message
b.
Before f: x = 6
an error message
c.
Before f: x = 6
Within f: x = 6
Within f: x = 12
After f: x = 12
d.
none of the above
it would if the # global x line wasn't commented out
Sorry I added that comment when I was messing around with the question. Let me give the original question
But as for why it doesn't access the global value, it's because a function cannot access both local and global at the same time
Even if the local variable is created after the line where it is trying to be accessed?
Yes. When a function is defined, it scans through it's code looking for any variable assignment. It knows ahead of time what local variables are expected to exist
OH
So if the function sees x = 12 anywhere in the function (and the global keyword wasn't used), then it knows x must be a local version of x
so if you try and use print(x) before the assignment, it doesn't know to look for the global x
it assumes that you're trying to access a local x
Thanks you for the explanation. What would the section in docs.python.org would this be explained more?
Thank you !
relevant literature here https://docs.python.org/3/reference/executionmodel.html#resolution-of-names
Thank you !
as usual (for anything except docs for specific functions) the python docs are boring to the point of effectively being useless, though
oh maybe not - the FAQ linked there is very useful
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.