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.

Signature

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.

#Initializing 
a=5
e1='a*a'
e2='min(10,20)'
#using eval function and printing
r1=eval(e1)
print("Result of e1 is ",r1)
r2=eval(e2)
print("Result of e2 is ",r2)

Output

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.

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

Output

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.

#Initializing 
e='a*a'
#using eval function and printing
r=eval(e)
print("Result of e is ",r)

Output

Traceback (most recent call last):
  File "main.py", line 3, in 
    r=eval(e) 
  File "", line 1, in 
NameError: name 'a' is not defined

Conclusion

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

References

Happy Learning 🙂

Leave A Comment