exec 和 eval
exec
exec语句用来执行储存在字符串或文件中的Python语句, 我们可以运行一个包含Python语句的字符串
>>> exec "print 'Hello Python'" Hello Python
但是exec可能会干扰Python语句的命名空间, 从而影响到原来的函数运行
>>> from math import sqrt >>> exec "sqrt = 1" >>> sqrt(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable
解决方案:
>>> from math import sqrt >>> temp = {} >>> exec "sqrt = 1" in temp >>> sqrt(4) 2.0 >>> temp['sqrt'] 1
eval
>>> eval(raw_input('input two number: ')) input two number: 2+3*5 17