eval() Builtin Function

Python – eval()

Python eval() builtin function takes an expression (as a string) which is then parsed and evaluated as a Python expression.

Syntax

The syntax of eval() function is

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

where

  • expression is a string value which is evaluated.
  • globals is an optional value. A dictionary of global variables.
  • locals is an optional value. A mapping object containing local variables.

Examples

Evaluate Python Expression which is in a String

In the following program, we take a string expression which contains a Python expression. We will use eval() function to parse this code and evaluate.

Python Program

code = "print('Hello World')"
eval(code)
Run

Output

Hello World

In the following program, we take an integer in variable x, and evaluate the expression 'x*x + 2*x + 5' using eval() function.

Python Program

x = 3
output = eval('x*x + 2*x + 5')
print(f'Output : {output}')
Run

Output

Output : 20

Summary

In this tutorial of Python Examples, we learned the syntax of eval() builtin function, and how to find evaluate a given expression, using eval() function with examples.