Walkthrough: Countdown
例题: 倒计时
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
- Evaluate the condition (
n > 0). - If False → exit, continue after the loop.
- 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.