Iteration in Python (Part II)

For Loop

Sometimes we want to loop through a set of things such as a list of words, the lines in a file or a list of numbers. When we have a list of things to loop through, we can construct a definite loop using a for statement. We call the while statement an indefinite loop because it simply loops until some condition becomes False whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.
The syntax of a for loop is similar to the while loop in that there is a for statement and a loop body:

friends = ['Ahmad', 'Ali', 'John']
for friend in friends:

    print ‘Happy New Year:’, friend

print ‘Done!

The for loop goes through the list (We will discuss list in details in future posts) and executes the body once for each of the three strings in the list resulting in this output:

Happy New Year: Ahmad
Happy New Year: Ali
Happy New Year: John

Often we use a for or while loop to go through a list of items or the contents of a file and we are looking for something such as the largest or smallest value of the data we scan through.
These loops are generally constructed by:

  • Initializing one or more variables before the loop starts.
  • Performing some computation on each item in the loop body, possibly changing the variables in the body of the loop.
  • Looking at the resulting variables when the loop completes.

To find the largest value in a list or sequence, we construct the following loop:

largest = None
print 'Before:', largest
for itervar in [3, 41, 12, 9, 74, 15]:

    if largest is None or itervar > largest :
      largest = itervar
    print ‘Loop:’, itervar, largest

print ‘Largest:’, largest
When the program executes, the output is as follows:

Before: None
Loop: 3 3
Loop: 41 41
Loop: 12 41
Loop: 9 41
Loop: 74 74
Loop: 15 74
Largest: 74