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.

Syntax

The syntax of exec() function is

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

where

  • object is a string or a code object which will be executed.
  • globals is an optional value. A dictionary of global variables.
  • locals is an optional value. A mapping object containing local variables.

Examples

Execute Python 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')
'''

exec(code)
Run

Output

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

Summary

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.