Quarry School

Stop a search at a match — quick review

In plain words

Someone looking for keys opens one drawer after another.

Rule

A break line ends the nearest loop around it at once, skips the rest of that pass and every later pass, and the program carries on with the first line after the loop. After a break, a for loop's name keeps its current item.

Step

  1. Above the loop, set any name that the program reads after the loop and that only a match changes, such as found = False.

  2. Write the test that marks a match, and put it in an if inside the body.

  3. Inside that if, do what the match needs, such as setting found = True, and then write break.

  4. Trace the passes until the test is true. At the break, jump to the first line after the loop.

  5. Check the case with no match. A for loop runs to its end, and a name that only a match changes, such as found, still holds the value it was given above the loop. A while True: loop that reads input and meets no match keeps reading; when the input runs out, input() stops the program with an EOFError.

Trap

A message about a miss written in the body after the match test runs on every pass that misses: in a search for a space, once for each character before the space, or once for every character of a string with no space. Decide after the loop, with a name such as found, whether the search found nothing.

In a while True: loop, the test never ends the loop. If the test before the break is never true for the replies typed, as when each reply is compared with "Done" and the person types done each time, the loop keeps asking. It stops only with an error: an EOFError when the input runs out, or a KeyboardInterrupt when you press Control-C, the interrupt key.