1

The following python code gives an error. Why isn't it referencing the global variable a ?

a = 10

def b(x):
    if(x == True):
        a = 2
    return a

print(b(False))

The error:

Traceback (most recent call last):
  File "<string>", line 8, in <module>
File "<string>", line 6, in b
UnboundLocalError: local variable 'a' referenced before assignment
> 
hari19
  • 95
  • 8

1 Answers1

0

The issue is that you're using a local variable that has the same name of the global one. This can help: Modifying global variable with same name as local variable

Edit: in fact, this seems to be working:

a = 10

def b(x):
    if(x == True):
        globals()['a'] = 2
    return a

print(b(False))
Leno
  • 186
  • 13
  • Yes, but my doubt was that python being a intepreter level language and the if condition being false, why is the a(local variable) inside if shadowing the global variable ? – hari19 Dec 19 '22 at 19:59