即使在执行后我也找不到执行的功能。
这是功能:
# function illustrating how exec() functions.
def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
exec(LOC)
print(factorial)
# Driver Code
exec_code()
但是,这会产生错误:
NameError Traceback (most recent call last)
<ipython-input-10-d403750cbbfb> in <module>
13
14 # Driver Code
---> 15 exec_code()
<ipython-input-10-d403750cbbfb> in exec_code()
10 """
11 exec(LOC)
---> 12 print(factorial)
13
14 # Driver Code
NameError: name 'factorial' is not defined
我真的很想像上面的模式那样执行一个字符串函数。有谁知道如何解决它?如果不推荐 exec,还有其他解决方案吗?