Python exec() Function

Executes a code block, expression to be evaluated, or single expression statement to be printed.

Syntax

Python
exec(source, globals, locals)

Parameters

ParameterDescription
source Required. A string, set of bytes or a CodeType returned from compile to be executed.
globals Optional. A dictionary whose name/value pairs represent global variables that can be accessed by the supplied code. The default is None.
locals Optional. A dictionary whose name/value pairs represent local variables that can be accessed by the supplied code. The default is None.

Example

Python
# A code block to be executed:
codeString = 'a = 5\nb = 6\nprint(f"{a} + {b} = {a + b}")'
codeObject = compile(codeString, 'add', 'exec')
exec(codeObject)

# An expression to be evaluated:
codeString = 'print(3 + 11)'
codeObject = compile(codeString, 'add', 'eval')
exec(codeObject)

# An "interactive" statement that will be printed
codeString = '7 * 3'
codeObject = compile(codeString, 'add', 'single')
exec(codeObject)

Output

5 + 6 = 11
14
21

Notes

Note that the exec() function always returns None. To return the value of an expression, use the eval() function.

Example

Python
# A code block to be executed:
codeString = 'a = 5\nb = 6\na + b'
codeObject = compile(codeString, 'add', 'exec')
print(exec(codeObject))

# An expression to be evaluated:
codeString = '3 + 11'
codeObject = compile(codeString, 'add', 'eval')
print(exec(codeObject))

Output

None
None