Python exec() Function: Learn to Execute Python Code | Syntax, Examples and Use Cases

Introduction: Python exec() Function

Some Python programs need to run Python code stored as text instead of writing it directly in the program. This is common in scripting tools, automation programs, code generators, and programs that create code while they run.

Running this code yourself requires extra code. The Python exec() Function makes this much easier.

What it is: The exec() function is a built-in Python function that runs Python code stored as a string or a compiled code object. Unlike eval(), it can run complete Python statements such as loops, function definitions, class definitions and multiple lines of code.

Take a look at a quick example to see how it works.

You can also explore its real-world use cases to learn where it is commonly used.

The next sections explain how the Python exec() Function works through its syntax, parameters, return value and examples.

💡 Tip: Use the exec() function only with trusted code because running unknown code can create security risks. To learn more built-in functions, visit the Python Built-in Functions Learning Guide.

Syntax, Parameters, Return Value and Examples: Python exec() Function

The following section explains the syntax, parameters, return value, and a quick example of the Python exec() Function.

Syntax

exec(object)

or

exec(object, globals)

or

exec(object, globals, locals)

Parameters

Parameter Description
object A string or compiled code object that contains valid Python statements.
globals (optional) A dictionary that defines the global namespace used while running the code.
locals (optional) A mapping object that defines the local namespace used while running the code.

Return Value

Return Value Description
None The exec() function does not return a value. It simply runs the given Python code.

Quick Example

The following example runs a Python statement stored as a string.

code = "print('Welcome to Python')"

exec(code)

# Output:
Welcome to Python

The string contains valid Python code. The exec() function runs that code, so the print() statement is executed just as if it had been written directly in the program.

How the Python exec() Function Works

  • The exec() function takes Python code as a string or a compiled code object.
  • Python runs the code while the program is running.
  • It can execute one statement or multiple statements.
  • Optional global and local namespaces let you control where variables are used.
  • The exec() function does not return a value.
  • If the code contains an error, Python raises the appropriate exception.

Examples: Python exec() Function

The examples below show different ways to use the Python exec() Function.

Example 1: Running a Single Python Statement

code = "print('Hello, Python!')"

exec(code)

# Output:
Hello, Python!

Explanation: The string contains one Python statement. The exec() function runs it, and the message is printed on the screen.

Example 2: Running Multiple Statements

code = """
x = 10
y = 20
print(x + y)
"""

exec(code)

# Output:
30

Explanation: The string contains more than one line of code. The exec() function runs each statement in order, just like normal Python code.

Example 3: Creating Variables with exec()

exec("number = 50")

print(number)

# Output:
50

Explanation: The executed code creates a new variable named number. After exec() finishes, the variable is available in the current program.

Example 4: Running Code with Custom Global Variables

code = "print(a + b)"

global_values = {
    "a": 15,
    "b": 25
}

exec(code, global_values)

# Output:
40

Explanation: Instead of using variables from the current program, this example provides its own global variables through a dictionary.

Example 5: Creating a Function Dynamically

code = """
def greet():
    print("Welcome!")
"""

exec(code)

greet()

# Output:
Welcome!

Explanation: The code inside the string creates a new function. Once the code runs, the function can be called like any other Python function.

Example 6: Running a Loop

code = """
for i in range(3):
    print(i)
"""

exec(code)

# Output:
0
1
2

Explanation: The exec() function is not limited to single statements. It can also run loops and other multi-line blocks of code.

Example 7: Handling Invalid Code

try:
    exec("for")
except SyntaxError as e:
    print(e)

# Output:
invalid syntax

Explanation: The code is incomplete, so Python cannot run it. A SyntaxError is raised. Using a try-except block prevents the program from stopping.

Use Cases: When to use the exec() Function

The Python exec() Function is useful in situations like these:

  • Running Python code stored as text.
  • Building scripting tools.
  • Creating automation programs.
  • Running dynamically created code.
  • Testing generated Python code.
  • Working with controlled scripting environments.

Key Takeaways: exec() Function

Here are the main points to remember about the Python exec() Function:

  • The exec() function runs Python code stored as a string or compiled code object.
  • It can execute complete Python statements and multiple lines of code.
  • It does not return a value.
  • Optional global and local namespaces can be provided.
  • It can create variables, functions, classes, and other Python objects.
  • Use it only with trusted code because running unknown code can be unsafe.

The exec() function is useful when a program needs to run Python code that is available as text. Since it can execute any Python statement, it should be used carefully and only with code from trusted sources.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top