Table of contents
Both functions have a common objective: to execute Python code from the string input or code object. Even though they both have the same objective, exec()
and eval()
are not the same.
Return Values
The exec()
function doesn't return any value whereas the eval()
function returns a value computed from the expression.
expression = "3 + 5"
result_eval = eval(expression)
print(result_eval)
result_exec = exec(expression)
print(result_exec)
When we run this code, we'll get 8
and None
. This means that eval(expression)
evaluated the result and stored it inside result_eval
whereas exec(expression)
returned nothing, so the value None
gets stored into result_exec
.
8
None
Execution
The exec()
function is capable of executing multi-line and multi-statment code, it doesn't matter whether the code is simple, complex, has loops and conditions, classes, and functions.
On the other hand, the eval()
function is restricted to executing the single-line code which might be a simple or complex expression.
expression = """
for x in range(5):
print(x, end=" ")
"""
exec(expression)
eval(expression)
Look at this code, we have a multi-line code that prints numbers up to the given range. The exec(expression)
will execute it and display the result but the eval(expression)
will display the error.
0 1 2 3 4
SyntaxError: invalid syntax
However, if we convert the same expression into a single line as the following, the eval(expression)
will not throw any error.
expression = "[print(x, end=' ') for x in range(5)]"
eval(expression)
--------------------
0 1 2 3 4
Summary
eval() | exec() |
Returns a value | Doesn't return any value |
Executes a single expression, it might be simple or complex | Capable of executing multi-statement and multi-line expressions containing loops, conditions, functions, and classes |
Use eval() when you need to evaluate a single expression and use its result. | Use exec() when you need to execute complex code blocks or multiple statements. |
🏆Other articles you might be interested in if you liked this one
✅Execute complex code blocks from string input using exec() function.
✅Template inheritance in Flask.
✅Type hints in Python - Callable objects, Return values, and more?
✅Best Practices: Positional and Keyword Arguments in Python
✅Yield Keyword in Python with Examples?
✅Create a WebSocket Server and Client in Python.
That's all for now
Keep Coding✌✌