Notes

`eval()` Function in Python [ English ]

< Prev Next >

1. Introduction

In Python, the eval() function is a built-in function used to evaluate and execute a Python expression that is written as a string. It reads the expression, evaluates it, and returns the result of that expression.

The function is useful when a program needs to dynamically execute expressions provided by the user or stored as strings.

However, since eval() executes the given string as Python code, it should be used carefully to avoid security risks, especially when dealing with untrusted input.

2. Syntax

eval(expression, globals=None, locals=None)

Parameters

  1. expression A string containing a valid Python expression that needs to be evaluated.

  2. globals (optional) A dictionary representing global variables available during evaluation.

  3. locals (optional) A dictionary representing local variables available during evaluation.

Return Value

3. Basic Example

x = eval("5 + 3")
print(x)

Output

8

Explanation

4. Example with Mathematical Expression

result = eval("10 * 5 + 2")
print(result)

Output

52

Explanation

5. Example with User Input

expression = input("Enter a mathematical expression: ")
result = eval(expression)

print("Result:", result)

Example Input

8 * 4 + 3

Output

Result: 35

Explanation

6. Example Using Variables

a = 10
b = 20

result = eval("a + b")
print(result)

Output

30

Explanation

7. Example with Lists

numbers = eval("[1, 2, 3, 4, 5]")
print(numbers)
print(type(numbers))

Output

[1, 2, 3, 4, 5]
<class 'list'>

Explanation

8. Example with Dictionary

data = eval("{'name':'Rahul', 'age':21}")
print(data)

Output

{'name': 'Rahul', 'age': 21}

Explanation

9. Security Consideration

Although eval() is powerful, it can be dangerous if used with untrusted input.

Example of a risky expression:

eval("__import__('os').system('ls')")

This can execute system commands, which may harm the system.

Therefore:

10. Difference Between eval() and exec()

Feature eval() exec()
Purpose Evaluates expressions Executes Python statements
Return value Returns result Does not return value
Usage Mathematical or logical expressions Full programs, loops, functions

Example:

eval("5 + 3")   # returns 8
exec("print(5 + 3)")  # prints 8

11. Summary

< Prev Next >