Journey to Master Python (WIP)


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Eval, Exec and Compile


Eval is used to evaulate dynamically generated python expression. It cannot evaluate statements. For example eval('10+5') is valid but eval('a=5') is not valid. This means it cannot be used to evaluate function definition, loops etc. It returns last executed expression.


Exec is used to execute dynamically generated python code. It always returns None. It can execute any python code like loop, function, class etc.


This might seem odd for a interpreted language. But this is used to compile code into python bytecode. It is used to speed up the repeated execution of a code.

Eval Exec Compile
# eval
a = eval('100*200')
print(f'Value of a is {a}')
b = exec('a = 100*200')
print(f'Value of a is {a} b is {b}')
# compiling the code
eval_compiled_code = compile('100*200', '<string>', 'eval')
exec_compiled_code = compile('a = 100*200', '<string>', 'exec')
a = eval(eval_compiled_code)
b = exec(exec_compiled_code)
# This is the quirky part. Eval can run exec compiled code and returns value
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content