exec() Builtin Function

Python – exec()

Python exec() builtin function takes Python code (as a string or as a code object) which is then parsed and executed.

In this tutorial, you will learn the syntax of any() function, and then its usage with the help of example programs.


The syntax of exec() function is

exec(object[, globals[, locals]])


objectA string or a code object
globals[Optional] A dictionary of global variables.
locals[Optional] A mapping object containing local variables.


1. Execute code present in a string

In the following program, we take a string code which contains a Python code. We will use exec() function to parse this code and execute dynamically.

Python Program

code = '''
for x in range(5):
    print(f'{x} - Hello World')

Run Code Online


0 - Hello World
1 - Hello World
2 - Hello World
3 - Hello World
4 - Hello World


In this tutorial of Python Examples, we learned the syntax of exec() builtin function, and how to find execute a given string of Python code, using exec() function with examples.

⫷ Previous tutorialNext tutorial ⫸