Python exec() Function



The Python exec() function allows dynamic execution of Python code. It can execute a string containing Python statements or a compiled code object. Generally, this function is used for running code generated by another part of the program.

Unlike the eval() function, which only accepts a single expression, the exec() function can accept single or multiple expressions or a large block of code.

The exec() is one of the built-in functions and does not require any module.

Syntax

Following is the syntax of the Python exec() function.

exec(object, globals, locals)

Parameters

The following are the parameters of the Python exec() function −

  • object − This parameter represents either string or code object.

  • globals − This parameter specifies a global function.

  • locals − This parameter indicates a local function.

Return Value

The python exec() function does not return any value.

exec() Function Examples

Practice the following examples to understand the use of exec() function in Python:

Example: Execute Single Expression Using exec()

The exec() function can be used to execute a single expression. The following is an example of the Python exec() function where we are trying to execute a simple print statement.

printStatement = 'print("Tutorialspoint")'
exec(printStatement)

On executing the above program, the following output is generated −

Tutorialspoint

Example: Execute Dynamic Code Using exec()

In this example, we will demonstrate how to execute a dynamic code with the help exec() function. Here, the method named "msg" accepts an argument dynamically and prints the result.

printStatement = """
def msg(name):
    print(f"This is, {name}!")
"""
exec(printStatement)
msg("Tutorialspoint")

The following is the output obtained by executing the above program −

This is, Tutorialspoint!

Example: Update Variable by Providing Expression to exec()

With the help of exec() function, we can modify a given value by performing arithmetic operations or by any other means as demonstrated in the below code block.

nums = 15
exec("res = nums + 15")
print("The result after execution:", res)

The following output is obtained by executing the above program −

The result after execution: 30

Example: Execute Looping Expression Using exec()

We can execute any small or large code block using the exec() function. In this example, we are running a for loop with the help of exec() function.

output = "for nums in range(5): print(nums)"
print("The result after execution:")
exec(output)

The above program, on executing, displays the following output -

The result after execution:
0
1
2
3
4
python_built_in_functions.htm
Advertisements