Python eval()

Python eval() builtin function is used to evaluate an expression that is given as a string. eval() can also execute code objects created by compile() method.

In this tutorial, we will learn about the syntax of Python eval() function, and learn how to use this function with the help of examples.

Syntax

The syntax of eval() function is

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

where

ParameterRequired/OptionalDescription
expressionRequiredA string. This expression is parsed and evaluated as a Python expression.
globalsOptionalA dictionary. This is used as global namespace.
localsOptionalAny mapping object. This is used as local namespace.

Returns

The function returns value of the given expression.

Example

Evaluate an Expression

In this example, we take a Python expression in a string, and pass it to eval() function for evaluation.

Python Program

x = 10
expression = 'x + 5'
result = eval(expression)
print("Result :", result)
Try Online

Output

Result : 15

Evaluate an Expression with Builtin Function

In this example, we take a Python expression in a string where the expression uses Python builtin function pow(), and pass it to eval() function for evaluation.

Python Program

x = 10
expression = 'pow(x, 3)'
result = eval(expression)
print("Result :", result)
Try Online

Output

Result : 1000

Evaluate an Expression with Global Values

In this example, we provide globals parameter to eval() function. Values for the variables in this dictionary are used for expression evaluation.

Python Program

x = 10
expression = 'pow(x, 3)'
globals = {'x': 5}
result = eval(expression, globals)
print("Result :", result)
Try Online

Output

Result : 125

Evaluate an Expression with Syntax Errors

If there are any syntax errors while parsing the expression, an exception is raised.

Python Program

x = 10
expression = 'x - a'
result = eval(expression)
print("Result :", result)
Try Online

Output

NameError: name 'a' is not defined

Conclusion

In this Python Tutorial, we have learnt the syntax of Python eval() builtin function, and also learned how to use this function, with the help of Python example programs.