Lets say I have the following function
def code_string(a):
for i in range(a):
exec('f=a+i')
print(f)
When I run it in the using the following command
code_string(3)
It gives me the following error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-9c91de8067f3> in <module>()
----> 1 code_string(3)
<ipython-input-2-2ae9915b0a25> in code_string(a)
2 for i in range(a):
3 exec('f=a+i')
----> 4 print(f)
NameError: name 'f' is not defined
when I run it not in the function as so
a=3
for i in range(a):
exec('f=a+i')
print(f)
It works perfectly fine as so
3
4
5
Why is this happening and can I execute a string code within a function in python
NOTE: This is only a demo example, please do not expect my code to be as simple as this demo example. I just put it to demonstrate the problem.