0

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.

1 Answer 1

1

You can try this:

def code_string(a):
    for i in range(a):
        exec('f=a+i', locals(), globals())
        print(f)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this, it worked but why it is important to mention locals and globals?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.