Sometimes a loop's task is finished before its final iteration. Using what we have seen so far, though, we still have to finish iterating. For example, to find which line in a file contains the string "Earth," we would have to write something like this:
current_line = 1 earth_line = 0
file = open("data.txt", "r") for line in file:
earth_line = current_line current_line = current_line + 1 print "Earth is at line %d" % earth_line
Here we require two variables: one for the current line number and another to remember the desired line number until after the loop. This is a little bit clumsy and also inefficient: if "Earth" is the first line of the file, this program is still going to read everything that comes after it.
'quit' to exit): CH3 'quit' to exit): H2O 'quit' to exit): quit
To fix this, we can exit the loop early using a break statement, which jumps out of the loop body immediately:
earth_line = 1
for line in file:
line = line.stripO if line == "Earth": break earth_line = earth_line + 1 print "Earth is at line %d" % earth_line
We can see this in Figure 7.10. Notice that because the loop exits early, the counter variable earth_line retains the value it had when the break was executed, so we need only one variable. However, if the file contains more than one occurrence of "Earth," this program will produce a different answer than the previous one. This program will display the index of the first line found, while the previous program would remember and display the index of the last matching line.
One more thing about break: it exits only the innermost loop that it's contained in. This means that in a nested loop, a break statement inside the inner loop will exit only the inner loop, not both loops.
Was this article helpful?