2

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

4 Answers 4

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

There is no way to use eval safely, that article is wrong. Read Eval Really is Dangerous for details.
Haha, yeah, I have actually completely avoided it solely due to reading others' comments on this site (and will continue to do so :) ).
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.