2

code1.py

if(__name__=="__main__"):
    var = "first_name"
    inp = "hello"
    exec("%s = '%s'" % (var,inp))
    print(first_name)

code2.py

def func():
    var = "first_name"
    inp = "hello"
    exec("%s = '%s'" % (var,inp))
    print(first_name)

if(__name__=="__main__"):
    func()

given two are two different codes code1.py works as expected. code2.py shows error

Traceback (most recent call last):
  File "bad.py", line 8, in <module>
    func()
  File "bad.py", line 5, in func
    print(first_name)
NameError: name 'first_name' is not defined

Can someone please explain why is this happening ?

srbcheema1
  • 544
  • 4
  • 16

0 Answers0