Python eval() Function
The eval() function evaluates and executes a Python code expression, returning the result of the expression.
Syntax
Python
Copy Code
eval(source, globals, locals)
Parameters
Parameter | Description |
---|---|
source |
Required. A string, set of bytes or a CodeType returned from compile to be executed. |
globals |
Optional. A dictionary whose name/value pairs represent global variables that can be accessed by the supplied code. The default is None. |
locals |
Optional. A dictionary whose name/value pairs represent local variables that can be accessed by the supplied code. The default is None. |
Example
Python
Copy Code
mySum = eval('5 + 6') print(mySum)
Output
11
Notes
Unlike the compile()
function, variables cannot be
assigned, but variables defined outside the expression can be used.
Example
Python
Copy Code
n = 31.006 codeString = 'n ** (1./3)' cubeRoot = eval(codeString) print(cubeRoot)
Output
3.141583309036842