At a Leeds fun run, how can your code show a result only for runners who finish?
You're writing the results program for a fun run in Leeds. You've got a list of runners, but some didn't finish. How can you write the code that shows a result just once, then run it once for each finisher?
You already know how to put a decision inside a loop. Here, the loop visits every runner in the list. For each runner, the decision checks whether they finished. If they did, show their result. If they didn't, move on without showing one.
Watch the highlight. The first line defines show Result without running its body. The call with Amira takes you into the body, where print displays ‘Amira finished’. When the procedure ends, control returns to the caller and moves to the next line, which prints ‘Next runner’.
You've just followed the call for Amira. The body has printed ‘Amira finished’ and reached its end. Which line will the program execute next? Pick the line the highlight should move to.
Above the main code, show Result displays a result without giving the caller a useful value. In Python, assignment introduces these names. Finished Reply names a fixed value by convention. Runners holds the list. Each pass assigns a name to runner and an answer to reply. A matching reply triggers the call.
Defining the procedure displays nothing. Amira's yes triggers a call. The procedure displays her result and returns to the caller, so the loop can continue. Ben's no skips the call, so no result appears for him. Carys's yes triggers another call and return. Add the calls: one plus zero plus one is two.
This time there are four runners. Their replies, in order, are no, yes, yes and yes. Follow the decision for each reply. How many times does the procedure body run? Pick an answer.
Here's a common tracing slip: counting the definition as an extra call. When Python reaches the line starting with def, it sets up the name and skips the body. A call such as show Result with Amira enters the body, displays her result and then returns to the caller.
Read the three pseudocode blocks from top to bottom. The count-controlled loop displays heat numbers one and two. The pre-condition loop reads a reply first, then repeats while it is invalid. If it is valid, the body is skipped. The post-condition loop reads at least once and stops on yes or no.