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 + 1means get the current value ofx, add 1, and then updatexwith the new value.
- Example:
- 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
- Example:
- Before updating, a variable must be initialized, typically with a simple assignment.
- Example:
python >>> x = 0 >>> x = x + 1
- Example:
- 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
whilestatement.Example:
n = 5 while n > 0: print(n) n = n - 1 print('Blastoff!')The
whilestatement continues execution as long as the condition is true. When the condition is false, the loop exits.Flow of execution:
- Evaluate the condition (True or False).
- If False, exit the
whilestatement. - 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
nis 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
breakstatement 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
breakwhen 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
breakstatement.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
continuestatement 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
continueis executed, the current iteration ends, and the program jumps back to thewhilestatement, skipping theprintstatement.
Definite Loops Using for
Use a
forstatement to loop through a set of items (e.g., list of words, lines in a file, numbers).The
whilestatement is an indefinite loop (it loops until a condition is false), while theforloop iterates through a known set of items.Syntax:
friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends: print('Happy New Year:', friend) print('Done!')The
forloop executes the body once for each string in thefriendslist.In English: "Run the statements in the body of the
forloop once for each friend in the set namedfriends."forandinare reserved keywords;friendandfriendsare variables.friendis the iteration variable, changing with each iteration and controlling when the loop completes.
Loop Patterns
fororwhileloops can be used to find the largest or smallest value in a list or file.- General structure:
- Initialize one or more variables before the loop.
- Perform a computation on each item, possibly changing the variables.
- 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)countis initialized to zero and incremented for each item in the list. At the end of the loop,countholds 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)totalis initialized to zero, and each number is added to it.totalaccumulates the sum of the elements (accumulator).Built-in functions
len()andsum()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)largeststores the largest value seen so far. Initialized toNone. IflargestisNone, the first value is assigned tolargest. After the first iteration,largestis 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)smalleststores the smallest value seen so far. Built-in functionsmax()andmin()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.