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.

In this tutorial, you will learn the syntax of any() function, and then its usage with the help of example programs.

Syntax

The syntax of eval() function is

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

where

Parameter Description
expression A string.
globals [Optional] A dictionary of global variables.
locals [Optional] A mapping object containing local variables.

Examples

1. Evaluate a statement 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 Code

Output

Hello World

2. Evaluate an expression which is in a string

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 Code

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.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us