Quiz: Repetition: Loops and Iteration
Test your understanding before moving on. Target: 70% or higher to proceed confidently.
Section 1: Multiple Choice (1 point each)
1. What values does range(3, 8) produce?
- A) 3, 4, 5, 6, 7, 8
- B) 3, 4, 5, 6, 7
- C) 4, 5, 6, 7
- D) 3, 4, 5, 6, 7, 8, 9
Answer
**B)** 3, 4, 5, 6, 7 *Why B:* `range(start, stop)` produces values from `start` up to but *not including* `stop`. So `range(3, 8)` gives 3, 4, 5, 6, 7 — five values. *Why not A:* 8 is excluded (the stop value is never included). *Why not C:* 3 is the start value and is included. *Why not D:* `range()` stops before the stop value, not after it. *Reference:* Section 5.2.22. How many times does the body of this loop execute?
for i in range(0, 10, 3):
print(i)
- A) 3
- B) 4
- C) 10
- D) 0
Answer
**B)** 4 *Why B:* `range(0, 10, 3)` produces the values 0, 3, 6, 9 — four values. (The next would be 12, which is >= 10, so it stops.) *Why not A:* There are four values, not three. *Why not C:* The step of 3 means not every integer from 0-9 is produced. *Why not D:* The range is valid and produces values. *Reference:* Section 5.2.23. Which loop is best suited for asking the user to re-enter input until it's valid?
- A)
forloop withrange() - B)
whileloop - C) Nested
forloop - D) Either
fororwhile— there's no difference
Answer
**B)** `while` loop *Why B:* You don't know how many invalid attempts the user will make, so the number of iterations is unknown. A `while` loop continues until a condition is met. *Why not A:* A `for` loop with `range()` requires knowing the number of iterations in advance. *Why not C:* Nesting is irrelevant to input validation. *Why not D:* While both can technically work, `while` is clearly more appropriate and idiomatic for condition-controlled repetition. *Reference:* Section 5.54. What is the output of this code?
total = 0
for num in range(1, 5):
total += num
print(total)
- A) 15
- B) 10
- C) 4
- D) 5
Answer
**B)** 10 *Why B:* `range(1, 5)` produces 1, 2, 3, 4. The sum 1+2+3+4 = 10. *Why not A:* 15 would be the sum of 1+2+3+4+5, but 5 is excluded from `range(1, 5)`. *Why not C:* 4 is the last value, not the sum. *Why not D:* 5 is the stop value (excluded), not the sum. *Reference:* Section 5.6.15. What does the break statement do?
- A) Skips to the next iteration of the loop
- B) Ends the program entirely
- C) Immediately exits the enclosing loop
- D) Pauses the loop for one second
Answer
**C)** Immediately exits the enclosing loop *Why C:* `break` terminates the current loop and continues execution after the loop. *Why not A:* That's what `continue` does. *Why not B:* `break` exits the loop, not the program. Code after the loop still runs. *Why not D:* Python has no built-in pause statement (you'd use `time.sleep()` for that). *Reference:* Section 5.7.16. What is the output of this code?
for i in range(5):
if i == 3:
continue
print(i, end=" ")
- A) 0 1 2
- B) 0 1 2 4
- C) 0 1 2 3 4
- D) 3
Answer
**B)** 0 1 2 4 *Why B:* When `i` is 3, `continue` skips the `print()` and moves to the next iteration. All other values (0, 1, 2, 4) are printed. *Why not A:* The loop doesn't stop at 3; it only skips 3. *Why not C:* The value 3 is skipped due to `continue`. *Why not D:* `continue` skips the current iteration, it doesn't select only that value. *Reference:* Section 5.7.27. In a nested loop where the outer loop runs 3 times and the inner loop runs 5 times, how many times does the inner loop's body execute?
- A) 3
- B) 5
- C) 8
- D) 15
Answer
**D)** 15 *Why D:* For each of the 3 outer iterations, the inner loop runs 5 times: 3 × 5 = 15. *Why not A:* 3 is only the outer loop count. *Why not B:* 5 is only the inner loop count per outer iteration. *Why not C:* Loop iterations multiply, not add. *Reference:* Section 5.8.18. Which of the following correctly describes the accumulator pattern?
- A) Initialize a variable inside the loop, update it outside the loop, use it during the loop
- B) Initialize a variable before the loop, update it inside the loop, use it after the loop
- C) Use
breakto accumulate values in a list - D) Use
range()to automatically sum a sequence
Answer
**B)** Initialize a variable before the loop, update it inside the loop, use it after the loop *Why B:* The three steps are: (1) initialize before, (2) update inside, (3) use after. *Why not A:* If you initialize inside the loop, the accumulator resets every iteration. *Why not C:* `break` exits loops; it doesn't accumulate. *Why not D:* `range()` generates values but doesn't sum them. *Reference:* Section 5.6.19. What is an infinite loop?
- A) A loop that runs exactly once
- B) A loop that iterates over an infinitely long list
- C) A loop whose exit condition is never met, so it runs forever
- D) A loop with more than 1,000 iterations
Answer
**C)** A loop whose exit condition is never met, so it runs forever *Why C:* An infinite loop occurs when the condition of a `while` loop never becomes `False`, or the loop has no mechanism to terminate. *Why not A:* A loop that runs once is just a normal loop with one iteration. *Why not B:* A list always has a finite number of items, so a `for` loop over it ends when the items run out, no matter how many there are (as long as the loop body doesn't keep adding to that same list). "Infinite" is about the exit condition, not the data size. *Why not D:* The number of iterations doesn't define infinite — a loop running 1 million times is fine if it eventually stops. *Reference:* Section 5.9.110. What is the output of this code?
for i in range(3):
for j in range(2):
print(f"{i}-{j}", end=" ")
print()
- A)
0-0 0-1on the first line,1-0 1-1on the second,2-0 2-1on the third - B)
0-0 1-0 2-0on the first line,0-1 1-1 2-1on the second - C)
0-0 0-1 0-2 1-0 1-1 1-2all on one line - D)
0-0 1-1 2-2all on one line
Answer
**A)** `0-0 0-1` on the first line, `1-0 1-1` on the second, `2-0 2-1` on the third *Why A:* The outer loop variable `i` stays constant while the inner loop variable `j` cycles through its full range. After the inner loop completes, `print()` creates a newline, and `i` advances. *Why not B:* The inner loop iterates `j`, not `i`, within each row. *Why not C:* The `print()` after the inner loop creates newlines between rows. *Why not D:* Both variables independently cycle through their ranges. *Reference:* Section 5.8.1Section 2: True/False with Justification (1 point each)
11. "range(5) produces the values 1, 2, 3, 4, 5."
Answer
**False** *Explanation:* `range(5)` produces 0, 1, 2, 3, 4 — five values starting from 0, stopping before 5. To get 1 through 5, you'd use `range(1, 6)`.12. "A while loop always executes its body at least once."
Answer
**False** *Explanation:* A `while` loop checks the condition *before* the first iteration. If the condition is `False` from the start, the body never executes. For example, `while False: print("hello")` never prints anything.13. "The else clause of a loop runs only when the loop exits due to a break statement."
Answer
**False** *Explanation:* It's the opposite. The `else` clause runs when the loop completes *without* encountering a `break`. If `break` is triggered, the `else` is skipped. Think of it as "no break" rather than "else."14. "The accumulator pattern requires the accumulator to be initialized to 0."
Answer
**False** *Explanation:* The initial value depends on the operation. For summing, use 0. For multiplying (like factorial), use 1. For finding a maximum, use the first value or a number smaller than anything in the data. For building strings, use `""`. The key is choosing an initial value that doesn't distort the result.Section 3: Short Answer (2 points each)
15. Explain in 2-3 sentences why an infinite loop is usually a bug, and describe how to identify one when your program is running.
Sample Answer
An infinite loop is usually a bug because the programmer intended the loop to terminate but the exit condition is never reached — typically because the loop variable isn't being updated correctly. You can identify one when your program appears to freeze, keeps printing the same output repeatedly, or consumes 100% CPU without progressing. To stop it, press Ctrl+C in the terminal. *Rubric — full credit requires:* - Explaining that the exit condition is never met - Describing at least one observable symptom - Mentioning Ctrl+C or a way to stop it16. Write the range() call that produces each sequence of values. Don't use any code besides range().
a) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 b) 5, 6, 7, 8, 9, 10 c) 10, 8, 6, 4, 2 d) 100, 200, 300, 400, 500
Sample Answer
a) `range(10)` b) `range(5, 11)` c) `range(10, 0, -2)` (or `range(10, 1, -2)`) d) `range(100, 501, 100)` (or `range(100, 600, 100)`) *Rubric — full credit requires:* - All four correct (note: there may be multiple valid stop values for some)17. A student writes this code to compute the average of 5 numbers entered by the user. Identify the bug and explain how to fix it.
for i in range(5):
num = float(input("Enter a number: "))
total = 0
total += num
average = total / 5
print(f"Average: {average}")
Sample Answer
The bug is that `total = 0` is *inside* the loop. Every iteration, `total` is reset to 0 before adding the new number. So `total` only ever holds the last number entered. The fix is to move `total = 0` above the `for` line — initialize the accumulator *before* the loop starts. Fixed code:total = 0
for i in range(5):
num = float(input("Enter a number: "))
total += num
average = total / 5
print(f"Average: {average}")
*Rubric — full credit requires:*
- Correctly identifying that `total = 0` is inside the loop
- Explaining the consequence (total resets each iteration)
- Providing the fix (move initialization before the loop)
Section 4: Code Tracing (2 points each)
18. Trace through this code and write the exact output.
result = 1
for i in range(1, 5):
result *= i
print(f"i={i}, result={result}")
Answer
i=1, result=1
i=2, result=2
i=3, result=6
i=4, result=24
Trace:
- `i=1`: result = 1 * 1 = 1
- `i=2`: result = 1 * 2 = 2
- `i=3`: result = 2 * 3 = 6
- `i=4`: result = 6 * 4 = 24
This computes 4! (four factorial).
19. Trace through this code and write the exact output.
x = 16
count = 0
while x > 1:
x = x // 2
count += 1
print(f"x={x}, count={count}")
Answer
x=1, count=4
Trace:
- Iteration 1: x = 16 // 2 = 8, count = 1
- Iteration 2: x = 8 // 2 = 4, count = 2
- Iteration 3: x = 4 // 2 = 2, count = 3
- Iteration 4: x = 2 // 2 = 1, count = 4
- Check: x=1, 1 > 1 is False, loop ends
This counts how many times you can halve 16 before reaching 1 (i.e., log base 2 of 16 = 4).
20. Trace through this code and write the exact output.
for i in range(4):
if i == 2:
break
print(i, end=" ")
else:
print("done")
print("after")
Answer
0 1 after
Trace:
- i=0: 0 != 2, print "0 "
- i=1: 1 != 2, print "1 "
- i=2: 2 == 2, `break` — exit loop immediately
- The `else` clause does NOT run because the loop was terminated by `break`
- "after" prints because it's outside the loop entirely
Note: "done" is never printed because `break` prevents the `else` from executing.
Scoring & Next Steps
| Score | Assessment | Recommended Action |
|---|---|---|
| < 50% | Needs review | Re-read sections 5.2-5.6, redo Part A and B exercises |
| 50-70% | Partial | Review weak areas, focus on accumulator pattern and range() |
| 70-85% | Solid | Ready to proceed; revisit any missed loop control topics |
| > 85% | Strong | Proceed to Chapter 6; consider the advanced exercises |