Linux/Unix > Python Essential Reference, Second Edition > 5. Control Flow > Loops | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104031089146150053204098

### Loops

You implement loops using the `for` and `while` statements. For example:

    while expression:
        statements

    for i in s:
        statements

The `while` statement executes statements until the associated expression evaluates to false. The `for` statement iterates over all the elements in a sequence until no more elements are available. If the elements of the sequence are tuples of identical size, you can use the following variation of the `for` statement:

    for x,y,z in s:
        statements

In this case, `s` must be a sequence of tuples, each with three elements. On each iteration, the contents of the variables `x` , `y` , and `z` are assigned the contents of the corresponding tuple.

To break out of a loop, use the `break` statement. For example, the following function reads lines of text from the user until an empty line of text is entered:

    while 1:
       cmd = raw_input('Enter command > ')
       if not cmd:
          break            # No input, stop loop
       # process the command
        ...

To jump to the next iteration of a loop (skipping the remainder of the loop body), use the `continue` statement. This statement tends to be used less often, but is sometimes useful when the process of reversing a test and indenting another level would make the program too deeply nested or unnecessarily complicated.As an example, the following loop prints only the non-negative elements of a list:

    for a in s:
        if a < 0:
           continue       # Skip negative elements
        print a

The `break` and `continue` statements apply only to the innermost loop being executed. If it’s necessary to break out of a deeply nested loop structure, you can use an exception. Python doesn’t provide a goto statement.

You can also attach the `else` statement to loop constructs, as in the following example:

    # while-else
    while i < 10:
         do something
         i = i + 1
    else:
         print 'Done'

    # for-else
    for a in s:
         if a == 'Foo':
              break
    else:
         print 'Not found!'

The `else` clause of a loop executes only if the loop runs to completion. This either occurs immediately (if the loop wouldn’t execute at all) or after the last iteration. On the other hand, if the loop is terminated early using the `break` statement, the `else` clause is skipped.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.