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

asked Aug 21, 2012 at 17:31

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)

answered Aug 21, 2012 at 17:37
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 :) ).

answered Aug 21, 2012 at 17:34

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
answered Aug 21, 2012 at 17:35

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

answered Aug 21, 2012 at 17:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.