Python eval() Function

Last Updated : 18 Apr 2026

In Python, the eval() function is an underlying Python function that evaluates a string as a Python expression. It takes a single parameter, which is a string that addresses a Python expression. The eval() function then evaluates this expression and returns the outcome. The python eval() function parses the expression passed to it and runs python expression(code) within the program.

The eval() function is in many cases used in Python to execute dynamically produced code. For instance, on the off chance that you have a string that contains a numerical expression, you can use the eval() function to evaluate that expression and return the outcome.

Syntax of eval() Function

It has the following syntax:

Parameters

  • expression: The string is parsed and evaluated as a Python expression.
  • globals (optional): A dictionary that specifies the available global methods and variables.
  • locals (optional): It is an another dictionary which is commonly used for mapping type in Python.

Return

It returns the result evaluated from the expression.

Examples of eval() Function

Here, we are going to discuss several examples that demonstrate the working of eval() Function.

Example 1: Using eval() Function to Evaluate Expressions

In this example, the eval() function is used to evaluate a string expression that includes variables and returns the computed result.

Output:

40

Explanation:

In this example, we have defined two variables x and y and introduced them with the values 15 and 25, separately. After that, we call the eval() function with the string 'x + y' as the expression. The eval() function evaluates this expression as the sum of the values of x and y, which is 40. At last, we print the outcome using the print() function.

Example 2: eval() Function with globals() and locals()

In this example, the eval() function is used with globals() and locals() to evaluate an expression within a specific scope, allowing access to both global and local variables.

Output:

20

Explanation:

In this example, we have defined two variables x and y, and a string expr that contains a Python expression. After that, we call the eval() function with the globals() and locals() functions as contentions, which address the global and local namespaces, separately. The eval() function evaluates the expression 'x + y' utilizing the globals() and locals() namespaces and returns the outcome, which is 20.

Example 3: eval() Function with Custom Local Variables

In this example, the eval() function is used with a custom local dictionary to provide additional variables, allowing the expression to be evaluated with values not directly defined in the code.

Output:

100

Explanation:

In this example, we have taken two variables x and y, and a string expression x + y + z. Since z is not defined directly, we pass its value using a dictionary. The eval() function then calculates the result using these values and returns 100.