Loop and a Half

Some programmers would solve the warning problem from the previous section using a slightly different style.

while 1:

number = input("Enter a positive number: ") if x >= 0: break # Loop exit print "The number you entered was not positive"

Here the loop exit is actually in the middle of the loop body. This is called a loop and a half. Some purists frown on exits in the midst of a loop like this, but the pattern can be quite handy.

The loop and a half is an elegant way to avoid the priming read in a sentinel loop. Here is the general pattern of a sentinel loop implemented as a loop and a half.

while 1:

Get next data item if the item is the sentinel: break process the item

Figure 8.3 shows a flowchart of this approach to sentinel loops. You can see that this implementation is faithful to the first rule of sentinel loops: avoid processing the sentinel value.

The choice of whether to use break statements or not is largely a matter of taste. Either style is acceptable. One temptation that should generally be avoided is peppering the body of a loop with multiple break statements. The logic of a loop is easily lost when there are multiple exits. However, there are times when even this rule should be broken to provide the most elegant solution to a problem.

+1 -2


  • amaranth
    What is a loop and a half on python?
    3 years ago

Post a comment