You are currently viewing Difference between exec() and eval() with Examples

Difference between exec() and eval() with Examples

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.

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.

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.

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.

However, if we convert the same expression into a single line as the following, the eval(expression) will not throw any error.

Summary

eval()exec()
Returns a valueDoesn’t return any value
Executes a single expression, it might be simple or complexCapable 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✌✌