Difference between exec() and eval() functions

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
Search for a command to run...

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
No comments yet. Be the first to comment.
When you’re building an application, one thing you can’t skip is API testing. Whether it’s a login flow, payment gateway, or a complex e-commerce workflow, ensuring your APIs behave correctly saves you from nasty surprises in production. I had alread...

PyPy is an implementation of Python written in RPython (Reduced Python) language, and it is seen as a replacement for CPython. PyPy claims that it is almost a drop-in replacement for CPython and can beat it on speed and memory usage. It supports libr...

You must have used functions provided by the os module in Python several times in your projects. These could be used to create a file, walk down a directory, get info on the current directory, perform path operations, and more. In this article, we’ll...

FastAPI is a fast and modern web framework known for its support for asynchronous REST API and ease of use. In this article, we’ll see how to stream videos on frontend in FastAPI. StreamingResponse Stream Local Video FastAPI provides a StreamingRespo...

Have you ever come across circular imports in Python? Well, it’s a very common code smell that indicates something’s wrong with the design or structure. Circular Import Example How does circular import occur? This import error usually occurs when two...
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.
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
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
| 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✌✌