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.
eval(expression, globals=None, locals=None)
Parameters
expression A string containing a valid Python expression that needs to be evaluated.
globals (optional) A dictionary representing global variables available during evaluation.
locals (optional) A dictionary representing local variables available during evaluation.
Return Value
x = eval("5 + 3")
print(x)
Output
8
Explanation
"5 + 3" is passed to eval().8 is returned and stored in x.result = eval("10 * 5 + 2")
print(result)
Output
52
Explanation
"10 * 5 + 2" is evaluated according to normal arithmetic rules.52 is returned.expression = input("Enter a mathematical expression: ")
result = eval(expression)
print("Result:", result)
Example Input
8 * 4 + 3
Output
Result: 35
Explanation
eval() evaluates the expression.a = 10
b = 20
result = eval("a + b")
print(result)
Output
30
Explanation
eval() can access variables that already exist in the program."a + b" is evaluated using the values of a and b.numbers = eval("[1, 2, 3, 4, 5]")
print(numbers)
print(type(numbers))
Output
[1, 2, 3, 4, 5]
<class 'list'>
Explanation
"[1, 2, 3, 4, 5]" is evaluated.data = eval("{'name':'Rahul', 'age':21}")
print(data)
Output
{'name': 'Rahul', 'age': 21}
Explanation
eval() evaluates the string as a dictionary.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:
eval() with user input from unknown sources.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
eval() evaluates a Python expression given as a string.