What is the exec() function in Python?

Overview

In Python, exec() is a built-in function used to run a dynamically generated program, which can be either a string or an object code.

Syntax

exec(object, globals, locals)

Parameters

  • object: This represents a string or code object.

  • globals: This represents the global functions. It can be a dictionary. This parameter is optional.

  • locals: This represents a local functions. It can be a mapping object. This parameter is optional.

Return value

This function returns no value.

Example

# create variable
num = 20
# compute in real-time and display result
exec('print("The value for num:", num **2)')

Explanation

  • Line 2: We create a variable, num, and assign value to it.

  • Line 4: We execute a string code using the exec() function.

Free Resources