Python Reference Library →

Python exec() Function – Execute Dynamic Python Code

Let’s look at exec() function – execute dynamic python code

  1. Notice

    exec() executes Python statements and returns None. A namespace can hold names created by those statements.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
namespace = {}
result = exec("number = 3", namespace)
print(result)
print(namespace["number"])
Live state

Top-level scope

namespace→Object 1
result→Object 2
Object 1 · dict{'number': 3}Object 2 · NoneTypeNone
This step

exec() executes Python statements and returns None. A namespace can hold names created by those statements.

Picture exec() function – execute dynamic python code

exec() executes Python statements and returns None. A namespace can hold names created by those statements.

Image brief

Alt text
A diagram for Python exec() Function – Execute Dynamic Python Code. Instructions: namespace = {} result = exec("number = 3", namespace) print(result) print(namespace["number"]). Displayed result: None 3. The final example bindings are namespace --> object 1 (dict); result --> object 2 (NoneType). object 1: {'number': 3}; object 2: None
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python exec() Function – Execute Dynamic Python Code". Teaching focus: exec() executes Python statements and returns None. A namespace can hold names created by those statements. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS namespace = {} result = exec("number = 3", namespace) print(result) print(namespace["number"]) | v DISPLAYED RESULT None 3 FINAL BINDINGS namespace --> object 1 (dict) result --> object 2 (NoneType) object 1: {'number': 3} object 2: None Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python exec() Function – Execute Dynamic Python Code. Instructions: namespace = {} result = exec("number = 3", namespace) print(result) print(namespace["number"]). Displayed result: None 3. The final example bindings are namespace --> object 1 (dict); result --> object 2 (NoneType). object 1: {'number': 3}; object 2: None

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
namespace = {}
result = exec("number = 3", namespace)
print(result)
print(namespace["number"])
Live state

Top-level scope

namespace→Object 1
result→Object 2
Object 1 · dict{'number': 3}Object 2 · NoneTypeNone
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
None
3

What do you expect this program to print?

What does this example display?

namespace = {}
result = exec("number = 3", namespace)
print(result)
print(namespace["number"])
What does this example display?
Choose one answer. You can try again.

Answer and explanation

None 3

Follow the printed values in order. The output is: None 3

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

exec() executes Python statements and returns None. A namespace can hold names created by those statements.

exec() executes Python statements and returns None. A namespace can hold names created by those statements.

More examples and reference

Python exec() Function

The exec() function in Python is used to execute dynamically created Python code. It takes a string as input and runs it as Python code.

This is a powerful tool, but it should be used carefully.

Syntax

exec(object[, globals[, locals]])

Parameters:

  • object – A string or code object that will be executed as Python code.
  • globals – (Optional) A dictionary to specify the global namespace.
  • locals – (Optional) A dictionary to specify the local namespace.

Returns:

  • None – It executes the code but does not return anything.

Example 1: Basic Use of exec()

code = "x = 5\ny = 10\nprint('Sum:', x + y)"
exec(code)
Sum: 15

Example 2: Defining a Function Dynamically

func_code = '''
def greet(name):
    print("Hello, " + name)
'''
exec(func_code)
greet("Alice")
Hello, Alice

Use Case: Why Use exec()?

  • Running Python code stored in a string or file
  • Creating functions or variables dynamically
  • Useful in applications like templates, config interpreters, or code evaluators

Security Warning

Never use exec() with untrusted input! It can execute arbitrary code and pose a serious security risk.

Example 3: Using globals and locals

global_scope = {}
exec("x = 100", global_scope)
print(global_scope["x"])
100

Common Mistakes

  • Using exec() when eval() would be safer and simpler
  • Passing unvalidated or user input to exec()
  • Expecting a return value – exec() doesn't return the result of expressions

Interview Tip

exec() shows up in questions around code generation, sandboxing, or dynamic behavior. It's powerful but should be avoided in production unless absolutely necessary.

Summary

  • exec() executes Python code passed as a string or code object
  • Returns None, modifies scope directly
  • Use carefully – it can run any code

Practice Problem

Ask the user for a math expression and evaluate it using exec().

expr = input("Enter a Python statement (e.g., print(2+3)): ")
exec(expr)

Note: Use eval() if you're only evaluating expressions (not statements).

What to remember

Connect what you noticed in the example with the idea below.

Remember

exec() executes Python statements and returns None. A namespace can hold names created by those statements.

Watch out for this idea

exec() returns the value of the last statement.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →