These questions follow Loops. A loop is a bargain with the computer: you describe one round precisely, it does all of them.
Questions
- Which of these needs a loop — (a) locking one door, (b) handing back 28 quizzes, (c) wearing boots if it rains?
- Predict the output — how many lines, and what is on each?
for number in range(4): print(number) - Trace
totalthrough every round, then predict what prints.total = 0 for number in range(1, 4): total = total + number print(total) - Find the bug. This countdown never reaches lift-off — or ends.
count = 3 while count > 0: print("T-minus", count) - Write a loop that prints
10down to1— countdown style. - Challenge. Keep asking
Password?until the user typessesame, then print how many attempts were needed.
Answers
Answer 1
Only (b) — one action, 28 repeats. (a) is a single step, and (c) is a decision: a job for a conditional, not a loop.
Answer 2
Four lines:
0,1,2,3.range(4)starts at 0 and stops before 4 — four numbers, none of them 4. Everyone trips on this.
Answer 3
totalgoes 0, then 1, then 3, then 6 —range(1, 4)supplies 1, 2, 3. Only6prints: the
Answer 4
Nothing inside the loop ever changes
count, soT-minus 3prints forever. Addcount = count - 1inside — it ends in three lines.
Answer 5
for number in range(10, 0, -1):thenprint(number)beneath. The third value steps by-1; the stop value0is never printed.
Answer 6
Start
attempts = 0andword = "". Thenwhile word != "sesame":readword = input("Password? ")and add 1 toattemptsinside the loop. Printattemptsafter — the loop only ends on success.
Curriculum connection
C2.4
write programs that include sequential, selection, and repeating events
Link to original
C1.5
identify and explain situations in which conditional and repeating structures are required
Link to original