-2

Case 1

A = '213'
def wow():
    print(A)
wow()
Output: '213'

Case 2

A = '213'
def wow():
    print(A)
    A = 12
wow()
Output: UnboundLocalError: local variable 'A' referenced before assignment

I'd thought that the output in the case 2 would be identical to the case 1, since A is a global variable and I called "print(A)" before reassigning value to A within the function. So my question is, why in the case 1 calling A is perfectly fine, but case 2 throws error?

iwbtrs
  • 358
  • 4
  • 13

1 Answers1

1

Because you are modifying it, so you would need global:

A = '213'
def wow():
    global A
    print(A)
    A = 12
wow()

global allows you to modify it too.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114