Chapter 5: Iteration

Updating Variables

  • A common pattern in assignment statements involves updating a variable, where the new value depends on the old.
    • Example: x = x + 1 means get the current value of x, add 1, and then update x with the new value.
  • Trying to update a non-existent variable results in an error because Python evaluates the right side before assignment.
    • Example:
      python >>> x = x + 1 NameError: name 'x' is not defined
  • Before updating, a variable must be initialized, typically with a simple assignment.
    • Example:
      python >>> x = 0 >>> x = x + 1
  • Incrementing a variable means increasing its value by 1; decrementing means decreasing it by 1.

The while Statement

  • Computers excel at automating repetitive tasks without errors.

  • Iteration is common, and Python offers language features to simplify it.

  • One form of iteration is the while statement.

  • Example:

    n = 5
    while n > 0:
        print(n)
        n = n - 1
    print('Blastoff!')
    
  • The while statement continues execution as long as the condition is true. When the condition is false, the loop exits.

  • Flow of execution:

    1. Evaluate the condition (True or False).
    2. If False, exit the while statement.
    3. If True, execute the body and return to step 1.
  • This flow is a loop; each execution of the body is an iteration.

  • The body should modify one or more variables so that the condition eventually becomes false, terminating the loop.

  • The iteration variable controls when the loop finishes. Without it, the loop may repeat forever (an infinite loop).

Infinite Loops

  • An infinite loop occurs when the terminating condition is never satisfied.

  • Example: "Lather, rinse, repeat" on shampoo bottles is an infinite loop because there's no iteration variable.

  • In a countdown, termination is guaranteed because the value of n is finite and decreases with each iteration, eventually reaching 0.

  • Sometimes, knowing when to end a loop requires reaching the middle of the body.

  • In such cases, create an infinite loop intentionally and use the break statement to exit.

  • Example of an infinite loop:

    n = 10
    while True:
        print(n, end='  ')
        n = n - 1
    print('Done!')
    
  • This loop runs until the program is forcibly stopped because the condition is always True.

  • This pattern can be useful if code is added to explicitly exit the loop using break when the exit condition is met.

  • Example: Taking user input until "done" is entered:

    while True:
        line = input('> ')
        if line == 'done':
            break
        print(line)
    print('Done!')
    
  • The loop continues until the user types "done", triggering the break statement.

  • This is a common approach because the condition can be checked anywhere in the loop, and the stop condition can be expressed affirmatively.

Finishing Iterations with continue

  • The continue statement skips the rest of the current iteration and jumps to the next one.

  • Example: Copying input until "done" is typed, but ignoring lines starting with “#”.

    while True:
        line = input('> ')
        if line[0] == '#':
            continue
        if line == 'done':
            break
        print(line)
    print('Done!')
    
  • When continue is executed, the current iteration ends, and the program jumps back to the while statement, skipping the print statement.

Definite Loops Using for

  • Use a for statement to loop through a set of items (e.g., list of words, lines in a file, numbers).

  • The while statement is an indefinite loop (it loops until a condition is false), while the for loop iterates through a known set of items.

  • Syntax:

    friends = ['Joseph', 'Glenn', 'Sally']
    for friend in friends:
        print('Happy New Year:', friend)
    print('Done!')
    
  • The for loop executes the body once for each string in the friends list.

  • In English: "Run the statements in the body of the for loop once for each friend in the set named friends."

  • for and in are reserved keywords; friend and friends are variables.

  • friend is the iteration variable, changing with each iteration and controlling when the loop completes.

Loop Patterns

  • for or while loops can be used to find the largest or smallest value in a list or file.
  • General structure:
    1. Initialize one or more variables before the loop.
    2. Perform a computation on each item, possibly changing the variables.
    3. Examine the resulting variables after the loop.

Counting and Summing Loops

  • Counting the number of items in a list:

    count = 0
    for itervar in [3, 41, 12, 9, 74, 15]:
        count = count + 1
    print('Count: ', count)
    
  • count is initialized to zero and incremented for each item in the list. At the end of the loop, count holds the total number of items.

  • Summing the numbers in a list:

    total = 0
    for itervar in [3, 41, 12, 9, 74, 15]:
        total = total + itervar
    print('Total: ', total)
    
  • total is initialized to zero, and each number is added to it. total accumulates the sum of the elements (accumulator).

  • Built-in functions len() and sum() can compute the number of items and the total of items, respectively.

Maximum and Minimum Loops

  • Finding the largest value in a list:

    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)
    
  • largest stores the largest value seen so far. Initialized to None. If largest is None, the first value is assigned to largest. After the first iteration, largest is updated only when a larger value is found.

  • Finding the smallest value in a list:

    smallest = None
    print('Before:', smallest)
    for itervar in [3, 41, 12, 9, 74, 15]:
        if smallest is None or itervar < smallest:
            smallest = itervar
        print('Loop:', itervar, smallest)
    print('Smallest:', smallest)
    
  • smallest stores the smallest value seen so far. Built-in functions max() and min() are available.

  • Simple version of the Python built-in min() function:

    def min(values):
        smallest = None
        for value in values:
            if smallest is None or value < smallest:
                smallest = value
        return smallest
    

Debugging

  • As programs grow, debugging becomes more time-consuming.
  • “Debugging by bisection” can reduce debugging time: Break the problem in half. Insert a print statement at the middle and check if it is correct. If not, repeat the process on the first half, otherwise on the second half.
  • Halve the number of lines to search with each check.
  • It's not always clear what the “middle of the program” is or possible to check it.
  • Think about potential error locations and easy-to-check spots.

Glossary

  • Accumulator: Variable that accumulates a result in a loop.
  • Counter: Variable that counts the number of times something happened in a loop. Initialized to zero and incremented.
  • Decrement: Update that decreases the value of a variable.
  • Initialize: Assigning an initial value to a variable that will be updated.
  • Increment: Update that increases the value of a variable (often by one).
  • Infinite loop: Loop with no terminating condition or one that is never satisfied.
  • Iteration: Repeated execution of a set of statements using a function that calls itself or a loop.

Exercises

  • Exercise 1: Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
  • Exercise 2: Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.