0

Why the following code doesn't work as it is but would work after commenting either print(x) or x=1?

def f():
    x = 1

    def g():
        print(x)
        x = 1
    g()

f()
MOHOSHA
  • 99
  • 8
  • With `print`, you are trying to access `g`'s local variable `x` before it is defined. Without it, you aren't. Locality doesn't change from statement to statement. – chepner Feb 13 '23 at 22:26
  • Because x = 1 is defined outside of `def g()` , in order to use it in the g() function you need to re-declare it as global. As it is python does not know if the x inside the g() def is a local variable you have declared that happened to shadow (have same name as) an outer variable or whether you meant to use the x defined outside of the function. – Galo do Leste Feb 13 '23 at 22:28
  • See also the FAQ in the docs: [_Why am I getting an UnboundLocalError when the variable has a value?_](https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value) – wim Feb 13 '23 at 22:28

0 Answers0