eval() Function in Python Example

Python3




print(eval('1+2'))
print(eval("sum([1, 2, 3, 4])"))


Output:

310

Simple Demonstration of eval() works

Let us explore it with the help of a simple Python program. function_creator is a function that evaluates the mathematical functions created by the user. Let us analyze the code a bit:

  • The above function takes any expression in variable x as input.
  • Then the user has to enter a value of x.
  • Finally, we evaluate the Python expression using the eval() built-in function by passing the expr as an argument.

Python3




def function_creator():
 
    # expression to be evaluated
    expr = input("Enter the function(in terms of x):")
 
    # variable used in expression
    x = int(input("Enter the value of x:"))
 
    # evaluating expression
    y = eval(expr)
 
    # printing evaluated result
    print("y =", y)
 
 
if __name__ == "__main__":
    function_creator()


Output:

Enter the function(in terms of x):x*(x+1)*(x+2)
Enter the value of x:3
y = 60

eval in Python

Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program.

Similar Reads

Python eval() Function Syntax

Syntax: eval(expression, globals=None, locals=None) Parameters: expression: String is parsed and evaluated as a Python expression globals [optional]: Dictionary to specify the available global methods and variables. locals [optional]: Another dictionary to specify the available local methods and variables. Return: Returns output of the expression....

eval() Function in Python Example

Python3 print(eval('1+2')) print(eval("sum([1, 2, 3, 4])"))...

Evaluating Expressions using Python’s eval()

...

Vulnerability issues with Python eval() Function

...

Making eval() safe

Evaluate Mathematical Expressions in Python...