I need to assign a numeric value, which is returned from a function, to a variable name by using exec() command:
def func1(x,y):
return x+y
def main(x,y,n):
x=3; y=5; n=1
t = exec("func%s(%s,%s)" % (n,x,y))
return t**2
main(3,5,1)
I have many functions like "func1", "func2" and so on... I try to return t = func1(x,y)
with theexec("func%s(%s,%s)" % (n,x,y))
statement. However, I cannot assign a value, returned fromexec()
.
There is a partly similar question on SE, but it is written for Python3 and is also not applicable to my case.
How can we resolve this problem or is there a more elegant way to perform such an operation, maybe without the use of'exec()'
?
By the way, as "func%s(%s,%s)" % (n,x,y)
is a statement, I used exec. Or should I better use eval?