(An Unofficial) Python Tutorial Wiki

putting the community back in "maintained by the community"

Beginners - Loops & Control Flow

COMMENT: This is part of a suggested restructuring of the Tutorial. Use the sidebar links to return to the current Tutorial.

  1. Intro
  2. Interpreter
  3. Numbers
  4. Strings
  5. Lists
  6. Dictionaries
  7. Control Flow
  8. Functions
  9. Classes

The if Statement

Perhaps the most well-known statement type is the if statement. For example:

>>> x = int(raw_input("Please enter an integer: ")) 
Please enter an integer: 5
>>> if x < 0:
...      x = 0
...      print 'Negative changed to zero'
... elif x == 0:
...      print 'Zero'
... elif x == 1:
...      print 'Single'
... else:
...      print 'More'
...
More

There can be zero or more elif parts, and the else part is optional. The keyword elif is short for else if, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.

Looping with for

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python's for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example:

>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...     print x, len(x)
... 
cat 3
window 6
defenestrate 12

The for loop maintains an internal loop variable, and you may get unexpected results if you try to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). To safely modify the list you are iterating over (for example, to duplicate selected items), you must iterate over a copy. The slice notation makes this particularly convenient:

>>> for x in a[:]: # make a slice copy of the entire list
...    if len(x) > 6: a.insert(0, x)
... 
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']

Looping with while

[TODO]

The range() Function

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates lists containing arithmetic progressions:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The given end point is never part of the generated list; range(10) generates a list of 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the step):

>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]

The enumerate() Function

To iterate over the indices of a sequence, use enumerate() as follows:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i, item in enumerate(a):
...     print i, item
...
0 Mary
1 had
2 a
3 little
4 lamb

The break and continue Statements

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

The continue statement, also borrowed from C, continues with the next iteration of the loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
...         # loop fell through without finding a factor
...         print n, 'is a prime number'
... 
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

The pass Statement

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

>>> while True:
...       pass # Busy-wait for keyboard interrupt
...

Previous (Dictionaries) - Next (Functions)


FAQS (http://pyfaq.infogami.com)