Lesson 24/48 ยท ๐Ÿ” Loops & Repetition
๐Ÿ” Loops & RepetitionLesson 24/48
Phase 3 ยท Loops & Repetition18 min

Trace the Code

Read code like a computer, the skill most courses never teach

Writing code is only half of programming. The other half is reading it.
When you join a team, you'll read 10 lines of code for every 1 you write. When you debug, you read. When you review a teammate's work, you read. When you study solutions online, you read.
Tracing is the skill of running code mentally, becoming the computer and predicting what happens step by step.
How to trace code:
1. Draw a variable table, two columns: name and current value2. Go through the code line by line, top to bottom3. When a variable is assigned, update your table4. When you reach a print(), write down what it would output5. For loops: repeat the process for each iteration
The goal is to predict the output before running it.
Example: trace this step by steppython
x = 5          # table: x=5
y = 2          # table: x=5, y=2
x = x + y      # table: x=7, y=2  (x was 5, add y=2, now 7)
print(x)       # output: 7
print(x * y)   # output: 14  (7 * 2)
Tracing a loop:
Loops require tracing each iteration (cycle). Make a new row in your table for each pass.
```pythontotal = 0for i in range(1, 4): total = total + iprint(total)`
| Iteration | i | total ||-----------|---|-------|| start | - | 0 || 1st | 1 | 0+1=1 || 2nd | 2 | 1+2=3 || 3rd | 3 | 3+3=6 |
Output: 6
The rule for loop tracing:
  • range(1, 4) produces 1, 2, 3, so 3 iterations
  • Each time: update i to the next value, then run the loop body
  • When the loop ends, total has the final value
  • ๐ŸŽฏ

    Phase Complete!

    Loops & Repetition

    Explain the difference between a `for` loop and a `while` loop. When would you choose one over the other? Give an example of each from the world of DevOps.

    0/500

    Practice Exercises

    0/3 solved
    Exercise 1 of 3easyTrace
    โฑ 00:00

    Trace: Simple Variables

    Trace this code mentally and type the exact output.Don't run it first, predict it!
    a = 10b = 3a = a - bb = b * 2print(a)print(b)
    solution.py
    1 / 3
    Exercise 2 of 3easyTrace
    โฑ 00:00

    Trace: A Loop

    What does this code print?
    total = 0for i in range(1, 5): total = total + iprint(total)
    Trace through each iteration, then enter the output:
    solution.py
    2 / 3
    Exercise 3 of 3mediumTrace
    โฑ 00:00

    Trace: Loop with If

    What does this code print?
    count = 0for i in range(5): if i % 2 == 0: count = count + 1print(count)
    Hint: range(5) gives 0, 1, 2, 3, 4. Which of those are even?
    solution.py
    3 / 3
    Solve all 3 exercises to unlock completion