Python Learning summary 17:exec and eval execution evaluation string

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.