Chapter 7: Iteration


Contents


This notebook is based on "Think Python, 2Ed" by Allen B. Downey
https://greenteapress.com/wp/think-python-2e/


Multiple assignment

  • You can assign a value to a variable as many times as needed
  • For example, this may be necessary in a loop
  • Don't forget that the difference between assignment (=) and an equality test (==)
  • Note that when you assign the value of one variable to another, it uses the value at that moment

In [1]:
a = 5
b = a    # a and b are now equal
a = 3    # a and b are no longer equal

Updating variables

  • As we have seen, multiple assignment usually occurs when you update a variable's value
  • Rmember, you have to initialize the variable before you use it

In [2]:
#x = x + 1    # Generates an error

x = 0
x = x + 1    # Works properly now
  • Adding 1 to a variable is referred to as incrementing the value
  • Subtracting 1 from a variable is referred to as decrementing the value
  • Other languages have operators that do this in one step, but Python doesn't

The while statement

  • We have previously discussed using a for loop for iteration
  • Python provides other options for iteration
  • The while loop can also be used

In [3]:
def countdown( n ):
    while( n > 0 ):
        print( n )
        n = n - 1
    print( 'Blastoff!' )
    
countdown( 5 )


5
4
3
2
1
Blastoff!
  • The loop continues while the conditional test n > 0 is true
  • Note that this can result in an infinite loop
  • While loops are often controlled via a single boolean variable
  • It is referred to as a sentinel variable
  • While you can have iteration with either a for or while loop, there are generally differences in how they are used
  • A for loop can be referred to as a definite loop
  • It is used when you know the number of times the loop should repeat before the loop is ever started
  • A while loop can be referred to as an indefinite loop
  • It is used when you don't know how many times a loop should repeat
  • Notice the difference between an infinite loop and an indefinite loop

Break statement

  • Sometimes you don't know you need to end a particular iteration of a loop until you are already inside it
  • In those situations, a break statement will allow you to break out of the loop

In [4]:
def echo():
    while( True ):
        line = input( '> ' )
        if( 'done' == line ):
            break
        print( line )
    print( 'Done!' )
  • This loop will continue to execute until the user enters the appropriate text
  • Although break statements can be useful, be careful
  • Overuse can lead to sloppy and confusing code
  • There are frequently better options if you take the time to think through the problem

Exercises

  • Build a program that implements a number guessing game. The program should be passed a high and low number. It should then generate a random number in between the high and low values. The program should then repeatedly prompt the user for a value, noting if the value was too high, too low, or correct. When the correct value is guessed, the program should terminate.

In [5]:
def start_guessing( low, high ):
    # INSERT YOUR CODE HERE
    print( 'Correct!' )
  • Write a function that calculates the sum of the squares of the first $n$ positive integers. The function should take the number n as an argument and return the sum.

In [6]:
def sum_squares( n ):
    # INSERT YOUR CODE HERE
    return 0
  • Write a function that computes the total amount of money you would receive if you received a penny a day doubled a day for a month. For example, on the first day you would get\ $0.01, on the second day you would get \\$0.02 (for a total of \$0.03), on the third day you would get \\$0.04 (for a total of \$0.07), and so on. Your function should take the number of days in the month as an argument and return the total amount of money you would receive. Furthermore, the function should print out the amount received for each day and the current total up to that day.

In [7]:
def double_money( days ):
    # INSERT YOUR CODE HERE
    return 0