The continue Statement

Another way to bend the rules for iteration is to use the continue statement, which causes Python to skip immediately ahead to the next iteration of a loop. For example, let's assume that the file data.txt could include comment lines starting with a # character:

Download loop/fileinput_continue_data.cmd

# Pluto is only 0.002 times the mass of Earth. Pluto


# Mars is half Earth's diameter, but only

# 0.11 times Earth's mass. Mars

Venus Earth Uranus

If we used the previous version of this program, it would count the commented lines as well, giving us an incorrect answer. Instead, we can use continue to skip comments in the file:

Download loop/filesearch_continue.cmd

entry_number = 1

for line in file :

line = line.stripO if line.startswith("#"):

continue if line == "Earth": break entry_number = entry_number + 1 print "Earth is the %dth-lightest planet." % (entry_number)

When continue is executed, it immediately begins the next iteration of the loop and skips any statements in the loop body that appear after it. This allows us to skip the statement where entry_number is incremented.

using continue is one way to skip comment lines, but this can also be accomplished by using the conditional statements that were introduced earlier in this chapter. In the previous code, continue prevents the comment line from being processed; in other words, if the line is not a comment, it should be processed.

Figure 7.11: The continue statement

The form of the previous sentence matches that of an if statement, and the updated code is as follows:

Download loop/

entry_number = 1

for line in file :

line = line.stripO if not line.startswith("#"): if line == "Earth": break entry_number = entry_number + 1 print "Earth is the %dth-lightest planet." % (entry_number)

Whether you favor if or continue is largely a matter of personal taste.2 As always, the most important thing is to be consistent: switching back and forth between the two is more likely to confuse your readers than consistently using either one.

2. That is our way of saying that the authors and reviewers of this book split almost evenly as to which they thought was better.

Style Notes M 153

Conditional statements give us control over of the flow of execution of our programs. When there are multiple paths of execution, we have choices to make about the structure of our conditional statements. For example, consider the following:

Download loop/

print 'bonjour' else:

print 'hola' else:

print 'Select a language.'

Under what conditions will "hi" be printed? "hola"? The word "hi" is printed when both a and b are True, and "hola" is printed when a is True, but b and c are not. To make this clearer, we can rewrite our conditional statement without the nesting:

Download loop/

print 'bonjour' elif a:

print 'hola' else:

print 'Select a language'

With multiple ways to write equivalent conditional statements, care must be taken to structure our code so that it is easy to understand. Reducing the amount of nesting is one way to improve the readability of the code, particularly if there are several nested conditionals.

break and continue have their place but should be used sparingly since they can make programs harder to understand. When people see while and for loops in programs, their first assumption is that the whole body will execute every time, in other words, that the body can be treated as a single "super statement" when trying to understand the program. if the loop contains break or continue, though, that assumption is false.

Sometimes, only part of the statement body will execute, which means the reader has to keep two scenarios in mind.

There are always alternatives: well-chosen loop conditions (as in Section 7.3, User Input Loops, on page 148) can replace break, and if statements can be used to skip statements instead of continue. It is up to the programmer to decide which option makes the program clearer and which makes it more complicated. As we said in Section 5.11, Comments, on page 103, programs are written for human beings; taking a few moments to make your code as clear as possible, or to make clarity a habit, will pay dividends for the lifetime of the program.

Was this article helpful?

0 0

Post a comment