Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python eval() Function

Python eval() Function

Python built-in function Python built-in function


Description

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

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

Syntax

The syntax of the eval() method is as follows:


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

Parameters

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.


Example

The following examples show the use of 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 a variable reference

x

=

10

result

=

eval

(

"x + 5"

)

print

(

result

)

 

Output: 15

Execute an expression in a 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 the expression, it may lead to code injection vulnerabilities. Therefore, the eval() function should be used with caution, and you should ensure that only trusted string expressions are executed.

Python built-in function Python built-in function