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 :) ).