0

If I make a code like:

lists = ["a='1'", "b='2'", "c=a+b"]
returned_list = []
for x in lists:
    exec(x)
print(c)

It works, and It print "12". but, If I use exec() in function:

lists = ["a='1'", "b='2'", "c=a+b"]
def test(lst):
    for x in lists:
        exec(x)

    print(c)
test(lists)

It returns NameError: name 'c' is not defined. How could I use exec() in function?

  • Does this answer your question? [exec() not working inside function python3.x](https://stackoverflow.com/questions/41100196/exec-not-working-inside-function-python3-x) – Tomerikoo Mar 14 '21 at 10:49

1 Answers1

0

When you assign a new variable in a function, you are actually assigning a variable in a scope which will be closed after the function is closed. Imagine it as a bubble with an item inside, which after the bubble blows, the item blows and disappears as well. It means, using exec() in a function would create a temporary local variable. But since functions have a predefined code, adding new variables to them without changing the code directly, would not be possible. in that case we need to use global keyword for each new variable in exec to make the variable save in the main and not in function. Therefor, your list would like this:

lists = ["global a\na='1'"]

also I'm not quite sure if you like the output of a+b be 12, if not, you can just remove the single quotes around each number such as "a=1" to make them integers

for further information check this and this

Ilia T.
  • 26
  • 4