Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python exec() Function



ThePython 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 theeval() function, which only accepts a single expression, theexec() function can accept single or multiple expressions or a large block of code.

Theexec() is one of thebuilt-in functions and does not require any module.

Syntax

Following is the syntax of the Pythonexec() function.

exec(object, globals, locals)

Parameters

The following are the parameters of the Pythonexec() function −

  • object − This parameter represents eitherstring or code object.

  • globals − This parameter specifies a global function.

  • locals − This parameter indicates a local function.

Return Value

The pythonexec() function does not return any value.

exec() Function Examples

Practice the following examples to understand the use ofexec() 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 simpleprint 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 performingarithmetic operations or by any other means as demonstrated in the below code block.

nums = 15exec("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 afor 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:01234
python_built_in_functions.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp