Iteration

From CS 61A Wiki
Revision as of 20:47, 14 June 2014 by Axis (Talk | contribs)


Jump to: navigation, search

Iteration is the process of repeatedly executing a block of code. The ability to execute a segment of code multiple times is necessary in complex programs. It helps minimize copying and pasting code — instead of writing the same lines of code over and over again, we can simply put those lines inside a loop. Almost every programming language (including Python) offers ways to loop over a part of code.

The while statement

The simplest form of iteration is the while statement. A while statement consists of a condition and a suite of statements:

while condition:
    # suite

A while statement executes its suite as long as condition evaluates to a True value. condition is checked each time before executing the suite again. If condition evaluates to a False value, execution continues with the statements after the while loop.

If the suite does not modify the variables being tested in condition, the loop will run forever. This is called an infinite loop. In the Python interpreter, press <Control>-C to terminate the program.

Simple example

The following while loop prints the numbers 0 – 5:

>>> i = 0
>>> while i <= 5:
...     print(i)
...     i += 1
... 
0
1
2
3
4
5

Example: First 10 Fibonacci numbers

One day Rohin challenges Andrew to find a way to write out first 10 Fibonacci numbers. The Fibonacci sequence is a mathematical sequence whose first two numbers are 1 and 1, and the following numbers are obtained by adding previous two numbers. Andrew can start with the first two values of the sequence, add those two numbers to create the 3rd number, add the 2nd and 3rd numbers to create the 4th, add the 3rd and 4th to create the 5th, and so on. He realizes that the problem can be solved iteratively, so he uses a while statement:

  1. i = 10
  2. previous = 0
  3. current = 1
  4. while i > 0:
  5.     previous, current = current, previous + current
  6.     i = i - 1
  7.     print(previous)

Recall that in the assignment previous, current = current, previous + current (line 5), the right side of the equals sign is evaluated first before making any assignment to previous or current. In this case, we evaluate current, and add previous and current, and then set previous to the value we got from evaluating current and set current to the result of the addition.

i = i - 1 (line 6) decrements i to make the while loop stop when i is 0 (i.e., make it execute 10 times).

The for statement

In languages such as Java and C, the for loop iterates over a range of values. By contrast, Python's for statement loops over elements of a sequence. The syntax is:

for elem in iterable:
    # suite

To execute a for statement:

  1. Evaluate iterable, which must yield an iterable (a fancy way of saying that it must return a valid sequence of items)
  2. For each element in that iterable (in order):
    1. Bind elem (you can call it whatever you want) to that value in the local environment.
    2. Execute the suite.

The above for statement is equivalent to:

iterator = iter(iterable)
while True:
    try:
        elem = next(iterator)
    except StopIteration:
        break
    # suite

Simple example

The following code prints each element of the list (recall that a list is an iterable):

>>> lst = [1, 2, 3]
>>> for elem in lst:
...     print(elem)
... 
1
2
3

Example: Iterating over a string

Andrew dares Rohin to pronounce the longest English word, Pneumonoultramicroscopicsilicovolcanoconiosis, without vowels. Rohin realizes that he can loop over all the characters of the word and print out only the ones that are not vowels, making it easier to pronounce:

vowels = "aeiou"
word = "pneumonoultramicroscopicsilicovolcanoconiosis"
for character in word:
    if character not in vowels:	
        print(character, end="") # optional 2nd argument is to print everything on one line

While loop vs. for loop

Generally, we use a while loop to execute a piece of code an indefinite number of times until a condition is met. The for loop is generally used repeat a piece of code n times (for each item of a sequence).

Nested loops

When we are using while or for statements to iterate, we can make nested loops by putting multiple for statements or while statements inside each other. This nested loop structure helps us iterate over a list of items inside another list of items.

See also

Sources