Python exec() Function



The python exec() function is a built-in function that 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.

In the next few sections, we will be learning more about this function.

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.

Examples

Now, let's understand the working of exec() function with the help of some examples −

Example 1

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 2

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 3

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 4

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