#πŸ”’ Global scope and UnboundLocalError

22 messages Β· Page 1 of 1 (latest)

primal gazelle
#

I need help understanding why the first line in the f() raises an error. My understanding is that it should refer to the x defined outside the function.

long palmBOT
#

@primal gazelle

Python help channel opened

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.

primal gazelle
#
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
sour cedar
primal gazelle
#

Sorry I added that comment when I was messing around with the question. Let me give the original question

sour cedar
#

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

primal gazelle
sour cedar
#

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

sour cedar
#

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

primal gazelle
#

Thanks you for the explanation. What would the section in docs.python.org would this be explained more?

sour cedar
#

I'm not sure really

#

it falls under the topic of "scope" though

primal gazelle
#

Thank you !

balmy void
balmy void
#

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

long palmBOT
#
Python help channel closed

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.