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.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources