• Loops are a way of repeating a block of code. You have to be aware that as you are repeating the loop, variables inside the loop change.
  • Often, you need to step through the code manually, with a debugger or print the values as they change to debug an error. I also recommend putting raw_input to enable stepping through the loop.

While loops

  • While loops require a stopping condition, which you must make sure will eventually be false. Otherwise you will get an infinite loop.

  • Basic syntax:

    while <condition is true>:
        do stuff
  • The most common ways to use a while loop is either a counter:

    i = 0
    while i < 10:
        print i
        i += 1

    or with a boolean:

    finished = False
    while not finished:
        cmd = raw_input("Next or stop to end => ")
        if cmd == 'stop':
            finished = True
            print "You entered", cmd

For loops

  • Fair warning: Python for loops are different than other languages.

  • For loops in Python iterate over a container of values.

    for item in L:
        print item

    This means that at each iteration, a value from L will be copied to the variable item and then the loop will be executed.

  • For loops works in the same way for many containers.

    1. Lists:

      animals = ['dog','cat','pig']
      for animal in animals:
          print animal

      Copy the string value for each item into variable animal, and execute the loop. Advance to the next index in the list, and continue.

    2. Sets (not in Exam #2, but hey why not):

      great_things = set(['puppies','hambergers','sleep'])
      for thing in great_things:
          print thing

      The effect is the same, except there is no ordering to the values in a set, so they will appear in some unpredictable ordering.

    3. Files (after you open a file, a for loop will simply be over the lines in the file):

      f = open('myfile.txt')
      for line in f:
          print line

      Remember that the variable line will have the new line in it. The loop will simply stop when you come to the end of the file.

      You can even combine the middle step of opening a file and iterating over the lines (Python is made for easy file processing!):

      for line in open('myfile.txt'):
          print line

For loops over indices (ranges)

  • If you want to change items in a list, it is necessary to iterate over indices and index an item. You can create indices with range.

  • The function range generates a list of values:


    You will generate ranges up to but not including the end point:

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

    If you skip start, you can only put the end point. It is assumed that you start at zero and increment by 1.

    >>> range(10)
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  • A frequent thing is to index items in a list. Remember list indices start with 0 and go up to the length of the list. So, this is the common use of range:

    L = ['a','b','c']
    for i in range(len(L)):
        L[i] = L[i].capitalize() + L[i]*3
    print L

Loops over complex objects

  • When you are iterating over complex objects using for loops, like lists of lists, you must be careful.

    L = [ ['fluffy','cat'], ['trigger','dog'], ['baxter','dog'] ]
    for item in L:
        print item
    print L

    Note that each item in this loop is actually a list. As a result, we do not copy lists to a variable when assigning, we alias them.

    This means that the above loop will actually change the list:

    >>> L
    [['fluffy', 'cat', 1], ['trigger', 'dog', 1], ['baxter', 'dog', 1]]
  • Compare the above one with this loop which does not change the list because item below at each iteration is a copy of the string in the list.

    L = ['fluffy','trigger','baxter']
    for item in L:
        item = item + '_cat'
        print item
    print L

    Confused? Read the section on aliasing.