I think too much emphasis is placed on the "kind" of loop (e.g while vs. repeat until), and on how to structure a while
loop if you need to pre fetch some values before you can consider exit condition(s).
Instead, I tutor my students about the infinite loop construct. And then about testing for exit condition(s), and advancing the loop (e.g. fetching), but that those two should occur in the order they naturally arise for the situation (and that we can have multiple exit conditions as needed).
I feel that the while and repeat-until constructs are false source-code optimizations and code should not be considered better for their use over more general looping constructs.
Using the infinite loop method tends to simplify mental task of writing a loop, since you can think about what to do inside the loop instead of how to write what you need in terms of one of the other more limited/specialized looping constructs before you even know what's needed. We also don't have to think in terms of priming before/outside the loop (with code that is then repeated inside the loop).
If it turns out that the exit test is at the beginning then it can be simply and mechanically transformed into a while loop, though I explain that they should not feel this transformation is necessary and might even have to be reversed/undone later (just like they should not feel it necessary to remove block {}
s for single line then and else statements).
If the language in question doesn't have an infinite loop construct I advocate while True ...
, for the infinite loop, so students can get onto the business of writing the loop instead of thinking about how to structure a loop they haven't even yet written as a while loop.
(The other loop construct I advocate is the counted/bounded for-loop, used when we know up front that some number of iterations are needed instead of a more general exit condition.)
Thus, my answer would be a third option:
while True:
answer=input("Do you wish to continue?")
if answer != "yes"
break;
print ("Good bye")
Compared with the first, it is DRY, and compared with the second, you don't require the students to fake the loop condition to "yes" before running the loop. (Yes, this could be transformed into a repeat-until, but I would say that is an uncessary transformation, though if done, could be done after writing the loop.)
do …while
, and combining assignment into a predicate has been shown to cause much confusion in professional programmers (I would expect the same for beginners). $\endgroup$answer
?while input( "Do you wish to continue?" ) == "yes": ...
$\endgroup$