Searching and stopping
Worked examples
Read the claim, then run it and check the machine agrees. One at a time — nothing here is taken on trust.
gap = 1.0
steps = 0
while gap > 0.01:
gap = gap / 2
steps += 1
print("steps:", steps)
print("gap :", gap)
Each pass halves gap and counts a step. The condition gap > 0.01 is
checked before every pass; once gap falls to 0.0078125 the check is
false and the loop stops — after 7 steps. The body changes gap every
time, which is exactly what guarantees the loop ends.
prices = [100, 101, 105, 98, 120]
first_over_104 = None
for i, p in enumerate(prices):
if p > 104:
first_over_104 = i
break
print("index:", first_over_104)
print("price:", prices[first_over_104])
enumerate gives index and value together. The scan hits 105 at index
2, records it, and breaks — so the answer is the first match, index 2,
not the last. Without break the loop would run on and (if you kept
overwriting) end up reporting the last match instead.
changes = [2, -3, 5, -1, 4]
up_total = 0
for c in changes:
if c < 0:
continue
up_total += c
print("up total:", up_total)
On negative days continue skips straight to the next item, so the add line
never runs for them. Only 2, 5 and 4 survive the filter, giving 11. Same
result as an if c >= 0: up_total += c — continue is just another way to
say "not this one".
Check the concept
One question at a time. Unsure? Revisit the lecture, then answer.
The challenge
Pass the quiz to unlock the challenge — your code will still be waiting here.