Back to Python
2026-02-115 min read

Python exec()

Learn Python exec() step by step with clear examples and exercises.

Why This Matters

Python's exec() function plays a crucial role in dynamic programming, allowing you to execute Python code as strings. This feature makes it an essential tool for various applications such as building code generators, executing user-provided code, and creating interactive shells. In this lesson, we will explore the core concept of exec(), delve into real-world examples, and provide practical exercises to help you master this powerful function.

Why This Matters

Dynamic programming is a technique where you can generate and execute Python code based on user input or other factors. With exec(), you can easily accomplish dynamic programming tasks without the need for complex workarounds. Understanding how to use exec() effectively will open up new possibilities in your Python programming journey.

Prerequisites

To fully understand this lesson, you should be familiar with the following topics:

  • Python basics: variables, data types, operators, functions, and control structures
  • Understanding the difference between static and dynamic programming
  • Familiarity with list comprehensions, lambda functions, and map function

Core Concept

Syntax and Basic Usage

The exec() function takes a string containing valid Python code as its argument and executes it. Here's the basic syntax:

exec(code_string, globals, locals)
  • code_string: A string containing Python code to be executed.
  • globals (optional): A dictionary representing the global namespace where variables and functions are defined. By default, it is equivalent to the built-in __global__ dictionary.
  • locals (optional): A dictionary representing the local namespace where variables are defined during function execution. If not provided, a new empty dictionary will be created for each call.

Here's an example of using exec() to execute a simple arithmetic expression:

Define code string

code_string = "result = 2 + 3"

Execute the code

globals()['result'] = None # Clear the result variable before execution

exec(code_string)

print("Result:", globals()['result']) # Output: Result: 5


### Dynamic Programming with exec()

One of the main use cases for `exec()` is dynamic programming, where you can generate and execute Python code based on user input or other factors. Here's an example of a simple calculator that takes user input and executes it:

def interactive_calculator():

print("Welcome to the Interactive Calculator!")

while True:

expression = input("\nEnter your expression (type 'quit' to exit): ")

if expression.lower() == "quit":

break

try:

globals()['result'] = None # Clear the result variable before execution

exec(expression)

print("Result:", globals()['result'])

except Exception as e:

print("Error:", e)

interactive_calculator()


### Generating Functions with exec()

In addition to executing simple expressions, you can also generate and execute entire functions using `exec()`. Here's an example of a function that generates Fibonacci sequence functions for a given number of terms:

def generate_fib_function(n):

fib_func = ""

fib_func += f"def fib({n}):\n"

fib_func += "result = 0\n"

if n > 1:

fib_func += f"a, b = 0, 1\n"

for i in range(2, n + 1):

fib_func += f"result, a = a, result + a\n"

fib_func += "return result"

return fib_func


Now let's generate and execute Fibonacci functions for 5 and 10 terms:

Generate Fibonacci function for 5 terms

fib_5 = generate_fib_function(5)

exec(fib_5, {}, {})

print("Fibonacci sequence (5 terms):", list(map(int, f"{globals()'fib'}".split(", "))))

Generate Fibonacci function for 10 terms

fib_10 = generate_fib_function(10)

exec(fib_10, {}, {})

print("Fibonacci sequence (10 terms):", list(map(int, f"{globals()'fib'}".split(", "))))

Worked Example

Let's create a simple code generator that generates and executes functions to calculate the factorial of a number using exec().

  1. Create a function to generate the factorial function for a given number:
def generate_factorial_function(n):
fact_func = ""
fact_func += f"def factorial({n}):\n"
fact_func += "result = 1\n"
for i in range(2, n + 1):
fact_func += f"result *= {i}\n"
return fact_func
  1. Generate and execute the factorial function for a given number:

Generate factorial function for 5

fact_5 = generate_factorial_function(5)

exec(fact_5, {}, {})

print("Factorial of 5:", globals()'factorial')

Common Mistakes

  • Not clearing the result variable before execution: If you don't clear the result variable before executing new code, it will retain the value from the previous execution. This can lead to unexpected results or errors.
  • Incorrect usage of globals and locals: Make sure to provide appropriate dictionaries for globals and locals when calling exec(). If you don't, you might encounter NameError or UnboundLocalError exceptions.
  • Not handling exceptions properly: When working with user input or dynamic code generation, it's essential to handle potential exceptions gracefully. Otherwise, your program may crash unexpectedly.
  • Ignoring the difference between compile() and exec(): compile() is used to compile Python code into bytecode, while exec() executes the compiled bytecode. Use exec() when you want to execute Python code as strings directly.

Practice Questions

  1. Write a Python script that generates and executes a function to calculate the sum of numbers in a list using exec().
  2. Modify the interactive calculator example to support basic arithmetic operations (addition, subtraction, multiplication, division) and parentheses for complex expressions.
  3. Write a Python script that generates a quadratic equation solver function using exec() based on user-provided coefficients.
  4. Create a code generator that generates a function to calculate the greatest common divisor (GCD) of two numbers using exec().
  5. Implement a simple interpreter for a custom programming language using exec(). The language should support basic arithmetic operations, variables, and user-defined functions.

FAQ

  1. Why do we need exec() when we can write functions dynamically?

While you can write functions dynamically using the compile() and eval() functions, exec() provides a more convenient way to execute entire blocks of code as strings, making it easier for dynamic programming tasks.

  1. Is it safe to use exec() with user-provided code?

Using exec() with user-provided code can be risky due to potential security issues like arbitrary code execution. It's essential to sanitize and validate the input before executing it to minimize these risks.

  1. Can I use exec() for performance optimization?

Using exec() for performance optimization is generally not recommended, as it can lead to slower execution due to the overhead of parsing and compiling strings into bytecode. Static programming is usually more efficient in terms of performance.

  1. What are some best practices when using exec()?

When using exec(), follow these best practices:

  • Sanitize user input before executing it to minimize security risks.
  • Use try-except blocks to handle potential exceptions gracefully.
  • Minimize the use of global variables and avoid modifying them excessively during execution.
  • Consider using other techniques like decorators or metaclasses for more complex dynamic programming tasks.
Python exec() | Python | XQA Learn