How do I execute a statement dynamically in Python?
For ex: assume the value x contains the following expression, (a+b)/2,
a = 1
b = 3
x = (a+b)/2
The value for x will be from a table
How do I execute a statement dynamically in Python?
For ex: assume the value x contains the following expression, (a+b)/2,
a = 1
b = 3
x = (a+b)/2
The value for x will be from a table
Probably you want eval
#!/usr/bin/env python
a = 1
b = 3
x = "(a+b)/2"
print eval(x)
But it's usually considered a bad practice (click here for a more elaborate and funnier explanation)
You can do:
a = 1
b = 3
x = '(a+b)/2'
print eval(x)
Note that the value for x
is enclosed in quotes as eval
requires a string or code object.
Also, perhaps read this to make sure you use it safely (as that can often be a concern and I'm not going to pretend to be an expert in its flaws :) ).
Although python has both "exec()" and "eval()", I believe you wan to use the latter in this case:
>>> a = 1
>>> b = 3
>>> x = "(a + b)/2"
>>> eval(x)
2
You can use eval, as in
eval(x)
Actually you can use
x=eval('(a+b)/2')
to get the result (eval will return the result of the computation in this case).