Difference between eval() and exec() in python

Keerti Prajapati
2 min readMay 16, 2021

I recently used eval() and exec() without even knowing how both the functions work and difference between them. Upon further investigation and learning I have found the main difference between eval() and exec(), in this short article I will be explaining those differences briefly.

Let’s start with simple definition of eval() and exec(),

eval(): It evaluate a string which contains single expression and return the calculated value

exec(): It execute a string which contains one or more expression or statements. It always returns None.

Eval vs Exec

  1. Return value:

Eval function evaluates the python code and returns the value, but Exec execute the code and always returns None,

Example: We are defining simple function , which will take two arguments and returns the summation,

def add(a,b):
return a+b

let’s see how eval and exec will work when we call the function with same parameters,

eval() returns the summation whereas there is no output for exec because it always returns None

2.Number of expression:

Eval() only evaluates the single expression, not the complex logic code, whereas Exec can be used to execute any number of expression.

exec() accept the source code which contains statements like, for, while, print, import

--

--