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()
给出两个是两个不同的代码 code1.py按预期工作。 code2.py显示错误
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
有人可以解释为什么会这样吗?