There may be times when you need to dynamically create Python code and then execute it as a statement or evaluate it as an expression.
1. exec
>>>exec"print ' Hello, world! ' " Hello, world!.
>>>fromimport sqrt>>>exec"sqrt=i" >>>sqrt (4) Traceback (most recent Call,ast): "<pyshell#18> " inch ? sqrt (4 is not callable:1
In the second example above, there is a case of interfering with an existing function, which requires the use of a namespace (or scope) to solve the problem; (or the name is inconsistent with the existing function name)
from Import sqrt>>> scope = {}exec'sqrt = 1' in scope >>> sqrt (4)2.0>>> scope['sqrt'
2. Eval
Eval (for "evaluation") is a built-in function similar to exec. The EXEC statement executes a series of pthon statements, and eval evaluates the Python expression (written as a string) and returns the result value (the EXEC statement does not return any objects because it is itself a statement). For example, you can use the following code to create a python calculator:
>>> eval (raw_input ("Enter an arithmetic expression:")]Enter an arithmetic expressipn:6+18 * 242
Like exec, Eval can also use namespaces. Although the expression is hardly re-assigned to a variable like a statement (in fact, it can provide two namespaces to the Eval statement, one local to the global. The global must be a dictionary, local can be any form of mapping).
>>> scope = {}>>> scope['x'] = 2>>> scope[' y '] = 3>>>eval ('x * y', scope)6
In fact, EXEC statements and eval statements are not commonly used, but they can be used as "powerful tools in the back pocket".
Python Learning summary 17:exec and eval execution evaluation string