Before the introduction of iterators in version 2.0, a common use of the break statement was to reading data from a file line by line. This technique is still useful if a file-like object does not support iteration.
try: f = open('filename','r') except IOError,msg: print 'Error opening filename: %s' % (msg[1]) sys.exit(1) while 1: line = f.readline() if not line : break # continue processing input lineSince assignments aren't allowed as while loop expressions, the value of 1, which is always guaranteed to be true, is used as the expression of the while loop; thus it is essential that a break statement is used somewhere in the body of the loop to insure that execution will eventually terminate. Here, we terminate execution of the loop when the readline method returns a value of None, signaling that it has reached the end of the file. Obviously, in loops of this sort, an else clause would never make sense, since the loop will never exit due to the while loop's expression taking on a false value.
The continue statement can be used in either for or while loops to instruct python to continue on to the next iteration of the loop without executing the statements in the loop which follow the continue statement. In a for loop, the value of the loop variable is incremented after a continue statement, so that after skipping the remaining part of the loop for the current iteration, the next iteration will be performed in the normal fashion.
Often a continue statement can be used as an alternative to an if statement inside a loop, and it's just a matter of personal preference as to which one is used. For example, suppose we wish to find the largest number in an array, as well as the index within the array at which the largest value occured. Using a continue statement, we could use the following:
>>> x = [7, 12, 92, 19, 18 ,44, 31] >>> xmax = x[0] >>> imax = 0 >>> for i in range(1,len(x)): ... if x[i] <= xmax : continue ... xmax = x[i] ... imax = i ... >>> print 'Maximum value was %d at position %d.' % (xmax,imax) Maximum value was 92 at position 2.Similar results could be obtained by putting the last two statements of the for loop as the clause of an if statement to be carried out when a new maximum value is found:
>>> for i in range(1,len(x)): ... if x[i] > xmax: ... xmax = x[i] ... imax = i ... >>> print 'Maximum value was %d at position %d.' % (xmax,imax) Maximum value was 92 at position 2.