🕯️ Magic Note
Unlike eval() which works only on a single expression and returns a value, exec() can run any Python code: multiple lines, loops, conditionals, function definitions, class creations, and imports. The code runs in the current scope (or a provided one) and can modify it.
- Can run multiple lines, loops, conditionals, and function definitions
- Returns None always, use side effects to see results
- Use \n to separate lines inside a string
- Accepts globals and locals dictionaries for controlled execution environments
| Feature | eval() | exec() |
|---|---|---|
| What it runs | Single expression | Multiple statements |
| Return value | The expression result | None |
| Can create variables | No | Yes |
| Example | eval(“3+5”) → 8 | exec(“x=3+5”) → None |
| Use case | Calculate from string | Run dynamic code blocks |
Python
# Running multiple statements
code = “””
total = 0
for i in range(5):
total = total + i
print(total)
“””
exec(code)
# Output: 10
Python
# Creating variables dynamically
exec(“greeting = ‘Hello, conjurer'”)
print(greeting)
# Output: Hello, conjurer
Python
# Defining functions with exec
exec(“””
def double(x):
return x * 2
“””)
print(double(7))
# Output: 14
- Expecting exec() to return a value, it always returns None
- Using exec() where a simple function or loop would work, making code harder to debug
- Running exec() on user input, creating a severe security vulnerability
⚡ Whisper
eval is a spark. Precise. Focused. Returning a single truth. exec is a fire. It spreads. It transforms. It leaves nothing unchanged. Both burn. Handle with silence and care.