Python Built-in Function eval():

The eval() is a built-in function that is used to evaluate an expression given as a string. In other words, if we have an expression stored as a string, we can evaluate it using the eval function.


The signature for the eval() function is as shown below. Here, this function takes one mandatory and two optional parameters. This function returns the result of an evaluated expression.

r=eval(expression, globals, locals)

Parameters and return type

  • Here, the expression argument is parsed and evaluated as a Python expression using the globals and locals dictionaries. The globals and locals are optional parameters that specify dictionary and mapping objects respectively.
  • However, it returns the result of an expression.

Python Built-in Function eval Examples:

Example 1: In this example, let us take an expression in the form of a string, and pass it to the function for evaluation. Here, we will also take an expression that makes use of the built-in function min(). Thereafter, We will pass this string to a function for evaluation.

#using eval function and printing
print("Result of e1 is ",r1)
print("Result of e2 is ",r2)


Result of e1 is  25
Result of e2 is  10

Example 2: In this example, let us demonstrate the use of a global dictionary. Firstly, we will take an expression as a string. Here, this expression makes use of the built-in function min. Thereafter, it evaluates the expression by fetching values from the globals dictionary. As a result, it finds the minimum of two values and prints the value.

e = 'min(a, 13)'
globals = {'a': 5}
#using eval function and printing
r = eval(e, globals)
print("Result of expression is ", r)


Result of expression is  5

Example 3: In this example, we will write an expression with some syntax errors in it. Here, as we can see variable a is not initialized with any value. So, it generates a NameError exception. As a result, the program terminates abnormally.

#using eval function and printing
print("Result of e is ",r)


Traceback (most recent call last):
  File "", line 3, in 
  File "", line 1, in 
NameError: name 'a' is not defined


The eval() function returns the result of an evaluated expression. However, it raises an exception, in presence of any syntax errors.


Happy Learning 🙂

Leave A Comment