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.

Syntax

The syntax of exec() function is

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

where

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

Examples

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

exec(code)
Run Code Copy

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.

Frequently Asked Questions

1. What does exec() function do in Python?

Answer:

exec() function takes Python code as argument in the form of string or a code object, parses the code, and then executes it.

exec('print(100)')

Related Tutorials

Code copied to clipboard successfully 👍