Python eval() Function

The eval() function in Python is used to evaluate the specified expression. For example:

x = 'print("fresherearth dot com")'
eval(x)

x = "print(100)"
eval(x)

x = "print(\"Welcome to Python\")"
eval(x)

The snapshot given below shows the sample output produced by this Python program, demonstrating the eval() function:

python eval function

Note: Unlike exec(), that executes dynamically generated code. The eval() function evaluates single dynamically generated expression.

Note: Unlike exec(), eval() only takes a single expression to evaluate.

Python eval() Function Syntax

The syntax of eval() function in Python is:

eval(expression, globals, locals)

where:

Note: Only the first parameter, that is the expression parameter is required. Whereas the other two parameters are optional

Note: The expression parameter is of String type.

Python eval() Function Example

Here is an example of eval() function in Python. This program receives a function in terms of x and then receives the value of x to evaluate the expression with given value of x:

print("Enter the Function (in terms of x): ", end="")
expression = input()
print("Enter the Value of x: ", end="")
x = int(input())

res = eval(expression)
print("\nResult =", res)

The sample run with user input x*x*x+x-x as function and 2 as value, is shown in the snapshot given below:

python eval function example

The eval() function in Python, can also be used to evaluate a function. Here is the program:

def msg():
    print("\nHey!\nWhat's Up?")

def table(num):
    print("\n-------Table of", num, "is---------")
    for i in range(1, 11):
        print(num, "*", i, "=", num*i)

print("Enter the Function: ", end="")
fun = input()
eval(fun)

The sample run with user input table(5) is shown in the snapshot given below:

python eval function program

Here is another sample run with user input msg() as function to evaluate:

eval function in Python

Important - Be sure to validate user input, when you're using user input for eval() method, as it may cause some serious issue to your application and related things. Because attacker may gives some harmful command as input to the function.

Python Online Test


« Previous Function Next Function »