Explaining
Code Behavior
Learn to trace through Python code step-by-step, predict outputs, and explain what happens using precise terminology.
Python
What Does "Explaining Code" Mean?
Explaining code behavior means walking through each line of a program in the order Python executes it, tracking how variables change, what operations occur, and what output is produced.
Why Tracing Code Matters
Debugging
When code breaks, tracing helps you find exactly where the logic went wrong.
Communication
Using correct terms lets you explain your code to teammates and teachers clearly.
Exam Success
AP CS and coding interviews require you to predict output without running code.
Core Python Terminology
Variable
A name that references a value in memory.
Assignment
Binding a value to a name using =.
Expression
Code that evaluates to produce a value.
Statement
A complete instruction Python executes.
Python's Execution Model
The Golden Rule of Tracing
1
Read the right-hand side expression.
2
Evaluate it: substitute current variable values and compute.
3
Assign the result to the left-hand side variable.
4
Move to the next line.
Expression vs. Statement
| Expression | Statement | |
|---|---|---|
| Definition | Produces a value | Performs an action |
| Example | \( 3 + 4 \times 2 \) | \( x = 10 \) |
| Can be nested? | Yes | No |
| Has a result? | Always | Not necessarily |
| Python example | \( \text{len}(\text{"hi"}) \) | \( \text{if } x > 0: \) |
The 5-Step Trace Method
1
Create a variable table: draw columns for each variable, plus one for output.
2
Read line 1: identify the statement type (assignment, print, if, loop, etc.).
3
Evaluate expressions: substitute current values, follow operator precedence.
4
Update the table: record new variable values and any printed output.
5
Advance: move to the next line (or follow control flow for loops/conditionals).
Example 1: Variable Swapping
Python
1a = 3 2b = 7 3a, b = b, a 4print(a, b)
1
a = 3
Assignment: the integer 3 is bound to the variable a.
2
b = 7
Assignment: the integer 7 is bound to the variable b.
3
a, b = b, a
Tuple packing/unpacking: the right side evaluates to (7, 3). Then a gets 7 and b gets 3.
4
print(a, b)
Function call: print outputs the current values of a and b.
Output
7 3
Example 2: Loop Accumulation
Python
1total = 0 2for i in range(1, 4): 3 total = total + i 4print(total)
| Iteration | \( i \) | total (before) | total (after) |
|---|---|---|---|
| 1st | \( 1 \) | \( 0 \) | \( 1 \) |
| 2nd | \( 2 \) | \( 1 \) | \( 3 \) |
| 3rd | \( 3 \) | \( 3 \) | \( 6 \) |
Output
6
Example 3: Functions & Conditionals
Python
1def classify(n): 2 if n % 2 == 0: 3 return "even" 4 else: 5 return "odd" 6 7result = classify(5) 8print(result)
7
result = classify(5)
Function call: Python jumps to classify, binding parameter n to 5.
2
if n % 2 == 0:
Evaluate: \( 5 \bmod 2 = 1 \), and \( 1 \neq 0 \), so the condition is False.
5
return "odd"
Return: the string "odd" is sent back to the caller. result now holds "odd".
Output
odd
Example 4: String Operations
Python
1word = "Python" 2first = word[0] 3last = word[-1] 4combo = first + last 5print(combo * 3)
1
word = "Python"
Assignment: word references the string "Python".
2
first = word[0]
Indexing: index \( 0 \) retrieves "P". first = "P".
3
last = word[-1]
Negative indexing: index \( -1 \) retrieves the last character "n".
4
combo = first + last
Concatenation: "P" + "n" = "Pn".
5
print(combo * 3)
String repetition: "Pn" \( \times \) \( 3 \) produces "PnPnPn", which is printed.
Output
PnPnPn
Tracing Scope Carefully
Python
1x = 10 2 3def add_five(): 4 x = 5 5 return x 6 7print(add_five()) 8print(x)
Output
5 10
Common Mistakes When Tracing
✕ Reading Left-to-Right
In \( x = x + 1 \), students read left to right. Python evaluates the right side first, then assigns.
✕ Ignoring Scope
Assuming a variable inside a function is the same as one outside. Local and global scopes are separate.
✕ Off-by-One in Loops
range(1, 4) produces 1, 2, 3: the end value is excluded. Not counting correctly ruins the trace.
Tracing Cheat Sheet
| Statement Type | What to Do | Key Term |
|---|---|---|
| Assignment | Evaluate right, store in left | Binding |
| Evaluate argument, write to output | Function call | |
| If / Elif / Else | Evaluate condition (True/False), enter matching branch | Conditional |
| For loop | Assign next value to loop variable, run body, repeat | Iteration |
| Function call | Jump to def, bind arguments to parameters, execute body | Invocation |
| Return | Send value back to caller, exit function | Return value |
Question 1 of 5
x = 5 x = x + 3 print(x)
▼ Tap to read code
What value is printed by this code?
Line 2 evaluates the right side: \( x + 3 \) = \( 5 + 3 \) = \( 8 \). That result is then assigned back to \( x \). The print statement outputs \( 8 \).
Question 2 of 5
for i in range(3):
print(i, end=" ")
▼ Tap to read code
What is the complete output?
range(3) produces the sequence \( 0, 1, 2 \) (three values, starting at \( 0 \), ending before \( 3 \)). Each value is printed with a space separator via end=" ".
Question 3 of 5
def mystery(a, b):
return a * b + 1
print(mystery(2, 3))
▼ Tap to read code
What does mystery(2, 3) return?
Python binds \( a = 2 \) and \( b = 3 \). The return expression evaluates: \( 2 \times 3 + 1 = 7 \). Multiplication has higher precedence than addition, so it is computed first.
Question 4 of 5
name = "Alice" greeting = "Hi, " + name + "!" print(len(greeting))
▼ Tap to read code
What is printed?
greeting = "Hi, " + "Alice" + "!" = "Hi, Alice!". Counting each character: H, i, comma, space, A, l, i, c, e, ! = \( 10 \) characters. len() returns the integer \( 10 \).
Question 5 of 5
x = 10
def change():
x = 20
return x
change()
print(x)
▼ Tap to read code
What value is printed?
Inside change(), \( x = 20 \) creates a local variable. It does not modify the global \( x \). Since the return value is not captured, the global \( x \) remains \( 10 \).