W WolfCode · CSC 141

Walkthrough: Countdown

例题: 倒计时

≈ 8 min · python-loops · Open in WolfCode

The textbook's first while-loop example, in 4 lines. The three-step flow of execution that every loop in CSC 141 follows.

The function

Python · runnable

The three-step flow

  1. Evaluate the condition (n > 0).
  2. If False → exit, continue after the loop.
  3. If True → run the body, then go back to step 1.

What makes it terminate

The line n = n - 1 (same as n -= 1) is the only reason this loop ever ends. Delete it and you have an infinite loop:

⚠ Don't actually run this — it will hang the browser. Trace it by hand.

The zero-iteration edge case

What does countdown(0) do?

Next

Sum 1..n uses the same shape — initialize before, update inside — but with a for loop instead of while.