-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?

Ilya Stokolos
  • 338
  • 1
  • 12

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.

U12-Forward
  • 65,118
  • 12
  • 70
  • 89