Example 1 — Run a Loop and Read the Result
Execute several statements in a fresh namespace and look at what exec() returns.
code = """
total = 0
for n in range(1, 5):
total += n
"""
namespace = {}
result = exec(code, namespace)
print(result)
print(namespace["total"]) How It Works
- Statements allowed. Assignments and a
forloop run exactly as in a file. - Returns None.
exec()does not hand back a value, even though the code computed one. - Results live in the namespace.
totalwas stored in thenamespacedict: 1 + 2 + 3 + 4. - Isolation. Your own variables are untouched because the code used its own dict.

