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.