Difference between eval and exec in Python

Sachin Pal
2 min readNov 14, 2024

--

Source: GeekPython

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

That’s all for now

Keep Coding✌✌

--

--

Sachin Pal
Sachin Pal

Written by Sachin Pal

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

No responses yet