Computer >> Computer tutorials >  >> Programming >> Python

How do I execute a string containing Python code in Python?


If you want to execute Python statements, you can use exec(string). For example,

>>> my_code = 'print "Hello World!"'
>>> exec(my_code)
Hello World!

But if you just want to evaluate the value of an expression, you can use eval(). For example,

>>> my_expression = "5 + 3"
>>> eval(my_expression)
8

 Note: Be very cautious while using both eval and exec as they are very powerful functions

and can cause very subtle bugs/ security loopholes in your code.