Skip to main content

exec()

The exec() function in Python is a built-in function that dynamically executes Python code. It takes either a string containing the Python code or a code object as an argument and executes it within the current scope. This function is often used for dynamic code execution and code evaluation.

Parameter Values

Parameter Description
object

This parameter represents either a string or code object. If it's a string, the Python code will be executed. If it's a code object, it will be executed in the current scope.

locals

This parameter is optional and represents a dictionary containing local variables. If provided, the code will be executed within this dictionary as the local namespace.

globals

This parameter is optional and represents a dictionary containing global variables. If provided, the code will be executed within this dictionary as the global namespace.

Return Values

The exec() function always returns None in Python.

How to Use exec() in Python

Example 1:

The exec() function in Python dynamically executes a string of Python code as a program.

code = "print('Hello, World!')"
exec(code)