Python eval() 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
- expression -- the expression.
- globals -- the variable scope and global namespace; if provided, it must be a dictionary object.
- locals -- the variable scope and 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.
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"
)
(
result
)
Output: 14
Execute a variable reference
x
=
10
result
=
eval
(
"x + 5"
)
(
result
)
Output: 15
Execute an expression in a specified namespace
namespace
=
{
'a'
:
2
,
'b'
:
3
}
result
=
eval
(
"a + b"
,
namespace
)
(
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