Python eval() Function

Python 内置函数Python Built-in Functions


Description

eval()The function is used to execute a string expression and return the value of the expression.

String expressionCan contain variables, function calls, operators, and other Python syntax elements.

Syntax

The following is the syntax for the eval() method:

eval(expression[, globals[, locals]])

Parameters

  • expression -- The expression.
  • globals -- Variable scope, global namespace. If provided, it must be a dictionary object.
  • locals -- Variable scope, local namespace. If provided, it can be any mapping object.

The eval() function parses the string expression as a Python expression and executes it in the specified namespace.

Return Value

The eval() function converts the string into the corresponding object and returns the result of the expression.


Examples

The following shows examples of using the eval() method:

Example 1

>>>x = 7 >>> eval( '3 * x' ) 21 >>> eval('pow(2,2)') 4 >>> eval('2 + 2') 4 >>> n=81 >>> eval("n + 4") 85

Example 2

# Execute a simple mathematical expression
result = eval("2 + 3 * 4")
print(result)  # Output: 14

# Execute variable reference
x = 10
result = eval("x + 5")
print(result)  # Output: 15

# Execute expression in the specified namespace
namespace = {'a': 2, 'b': 3}
result = eval("a + b", namespace)
print(result)  # Output: 5

Note:The code executed by the eval() function has potential security risks. If an untrusted string is used as an expression, it may lead to code injection vulnerabilities. Therefore, the eval() function should be used with caution, and ensure that only trusted string expressions are executed.

Python 内置函数Python Built-in Functions

Other Extensions