I want to use "exec" to compress many lines of code. But since the project I am working on is somewhat complex, I will simplify my code.
Let's suppose I want to make a function that will add me 3 numbers, one could easily write:
def sum3(a,b,c):
return a+b+c
But since the project I'm working on involves many more variables and more dynamic code, let's say we want that function to use "exec". My attempt to use it was as follows:
def suma_eval(a,b,c):
suma=0
for item in ("a","b","c"):
exec(f'''suma+={item}''')
print(f"""suma+={item}""")
return suma
It doesn't work. What did I do wrong?
UPDATE #1:
I already put it in a line as you indicated, the error stopped, but the result is a 0, when it should be 73. That is, the function is not working as expected.
UPDATE #2:
My problema has been solved, thank you so much, this is the answer:
def suma_eval(a,b,c):
suma=0
ldict={}
for item in ("a","b","c"):
exec(f'''suma+={item}''',locals(),ldict)
suma=ldict["suma"]
return suma