0

Here is the example Python code:

def second():
    print(x)
    x += 1
    print(x)


def first():
    print(x)
    second()

if __name__ == '__main__':
    x = 'Test'
    first()
    print(x)

'x' is visible in the first function call, but not in the second. If 'x' is global, why can't it be seen in the second? If 'x' isn't global, how is it being seen in the first function call?

mjj2u2
  • 29
  • 5
  • Did you *try googling the error message*, because probably hundreds of relevant duplicate stack overflow questions come up... in any case, see the linked duplicate. An assignment *anywhere* in a function body makes the variable local to taht function, you would need to use a `global` statement in `second` (although, not in `first`) – juanpa.arrivillaga Oct 26 '21 at 22:12
  • Also, this is addressed in the [official FAQ](https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value) – juanpa.arrivillaga Oct 26 '21 at 22:15

0 Answers0