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

user1050619
  • 19,822
  • 85
  • 237
  • 413

4 Answers4

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)

Community
  • 1
  • 1
Savir
  • 17,568
  • 15
  • 82
  • 136
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 :) ).

RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
  • There is no way to use eval safely, that article is wrong. Read [Eval Really is Dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) for details. – Ned Batchelder Aug 21 '12 at 21:31
  • Haha, yeah, I have actually completely avoided it solely due to reading others' comments on this site (and will continue to do so :) ). – RocketDonkey Aug 21 '12 at 21:37
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
D.C.
  • 15,340
  • 19
  • 71
  • 102
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).

hochl
  • 12,524
  • 10
  • 53
  • 87