Python's eval, exec summary of function usage

Source: Internet
Author: User
Tags function definition

Eval function

function of Functions

Evaluates the string str as a valid expression and returns the result of the calculation. The Python code it executes can only be a single operation expression (which does not support arbitrary assignment operations), not complex code logic.

Second, the definition of function

eval (expression, Globals=none, Locals=none)

Parameter description:

Expression: A required parameter, either a string or an arbitrary instance of the code object (which can be created through the compile function). If it is a string, it is parsed and interpreted as a python expression.

Globals: An optional parameter that represents the global namespace (which holds the global variable) and, if provided, a Dictionary object.

Locals: An optional parameter that represents the current local namespace (which holds local variables) and, if provided, can be any mapping object. If the parameter is ignored, then it will take the same value as globals.

If both Globals and locals are ignored, they will take the global namespace and local namespace of the eval () function called environment.

return value:

if Expression is a codecompile when the song body" "> object mode parameter is ' EXEC ' So Eval () none

Otherwise, if expression is an output statement, such as print (), eval () Returns the result of None

Otherwise, the result of expression expressions is the return value of the eval () function

Three, to give a few chestnuts

(1) Evaluates a valid expression in a string and returns the result

[CPP]View PlainCopy
    1. >>> eval (' pow (2,2) ')
    2. 4
    3. >>> eval (' 2 + 2 ')
    4. 4

(2) converts a string into a corresponding object (such as A conversion between list, tuple, dict, and string)

[Python]View PlainCopy
  1. >>> a = "[[+], [3,4], [5,6], [7,8], [9,0]]"
  2. >>> B = eval (a)
  3. >>> b
  4. [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
  5. >>> A = "{1: ' xx ', 2: ' yy '}"
  6. >>> C = eval (a)
  7. >>> C
  8. {1: ' xx ', 2: ' yy '}
  9. >>> a = "(1,2,3,4)"
  10. >>> d = eval (a)
  11. >>> D
  12. (1, 2, 3, 4)

(3) Changing the value of a variable

[CPP]View PlainCopy
  1. x = 10
  2. def func ():
  3. y = 20
  4. A = eval (' x+y ')
  5. Print "A=", a
  6. b = eval (' X+y ', {' x ': 1, ' Y ': 2})
  7. Print "b=", b
  8. c = eval (' X+y ', {' x ': 1, ' Y ': 2}, {' y ': 3, ' Z ': 4})
  9. Print "c=", C
  10. Func ()



Output:

A= 30

B= 3

C= 4

EXEC function

function of Functions

Dynamic execution of Python code that can execute complex python code

Second, function definition

EXEC (object[, globals[, locals]]

Parameter description:

Object: A required parameter that represents the python code that needs to be specified , which must be a string or a code object. If object is a string, the string is parsed into a set of python statements before being executed. If object is a code object, then it is simply executed

Globals: Optional parameter, same as eval function

Locals: Optional parameter, same as eval function

return value:

The return value of the EXEC function is always None

Three, chestnuts

(1) example 1

Because the Exec return value is None

So a = EXEC (' x+y '), this code will error.

Instead of exec (' x+y '), it can be executed normally

and d = eval (' Print (x, y) '), this code will error

Change to D = Exec (' Print (x, y) ')for normal execution

(2) Example 2

[Python]View PlainCopy
  1. x = Ten
  2. Expr = "" "
  3. z = 30
  4. sum = x+y+z
  5. Print (sum)
  6. """
  7. def func ():
  8. y =
  9. exec (expr)
  10. exec (expr, {' x ': 1, ' y ': 2})
  11. exec (expr, {' x ': 1, ' y ': 2}, {' y ': 3, ' z ': 4}) /c1>
  12. Func ()



Output:

60

33

34

For the output of the last result, why Z is not 4, comb the execution process as follows:

[Python]View PlainCopy
    1. x=1
    2. y=2
    3. def func ():
    4. y=3
    5. z=4
    6. z=
    7. Sum=x+y+z
    8. print (sum)
    9. Func ()



The eval () function differs from the EXEC () function:

The eval () function evaluates only the values of a single expression, and the exec () function can run code snippets dynamically

The eval () function can have a return value, and the exec () function return value is always None

Original: 75049938

Python's eval, exec summary of function usage

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.