Lab 7 - More Loops

Part 0 - Help us

At the end of the term, you will have a chance to provide feedback on the course and your professor through the ISU Class Climate system. We would like you to have a chance to provide feedback on your TA and the lab as well!

Before proceeding to the rest of the checkpoints, please take a minute to fill out this brief, anonymous survey.

Begin survey

When you are done, keep the confirmation page open to show your TA in Checkpoint 1.

Introduction

In the previous lab, we used loops in a very simple way: to repeat a turtle’s action some fixed number of times, for example, to draw the side of a polygon. This use of a loop is similar to the example below, which prints three “cheers” as output.

We also noticed that, in addition to just repeating a fixed action, a loop variable such as the variable count in the example above can be accessed and used within the loop body. For example, the code below prints numbers from 0 to 10.

In Python, we can use a for-loop to print a sequence of values. For example to print numbers from 1 to 10, we can use the below code:

If you step through the loop in codelens, you’ll see the at the loop variable num takes on a new value each time the loop body executes, namely, the values 0 through 9 that are represented by range(10).

We can do the same with any kinds of lists in Python, not just ranges. For simple examples, we can make a list just by putting some values within square brackets, separated by commas. Here’s an example:

Similarly we can iterate over a string and examine the characters one at a time:

In the rest of the lab we will be practicing how to use loops in a much more powerful way, in which we alter the values of other variables as the loop executes. In the most common patterns, we call such a variable an accumulator or counter.

Part 1: Accumulator Pattern

Sum of elements in a range

Below is an example to compute sum of numbers in a range

Here we use a loop to add the numbers from 1 - 10. In each iteration, number generated is added to the total. The variable total, gets updated in every iteration, “accumulating” the sum of all values.

The increment operator “+=”

We have previously used the statement

total = total + num

We’re taking the variable total, adding a value to it, and then storing the result back in the variable total. This kind of thing happens so often that there is a shorthand notation for it. The statement above could be written as

total += num

Using a product instead of a sum

The auxiliary variable that we update in the loop (such as total above) doesn’t have to be updated by addition. As another example, we could use multiplication. Here is a simple way to print powers of 2, that is, the sequence 1, 4, 8, 16, 32, ....

Checkpoint 1

  1. Write a function that, given n, prints out the first n values in the sequence 1, 2, 4, 7, 11, 16... (each iteration adds a value, but the value increases by 1 each time)
  2. Write a function calc_interest(amount, rate, years) that adds given percentage of interest to the amount for each year (up to given years). Each year, the amount is updated by adding amount * rate. After the given number of years, the function returns the new amount. As an example, calc_interest(100.0, .10, 2) returns 121.0, since it would add 10.0 the first year, to make 110.0, and then add 11.0 the second year, to make 121.0.
  3. Draw a spiral with turtle in which the turtle turns left after moving forward 10 pixels, where the turn angle starts at 90 degrees and decreases by 2 degrees each iteration. Try it for 50 iterations. Try it for 100 iterations.
  4. Show the TA the confirmation page from submitting the survey. Thank you!

Part 2

Tracing execution of a loop

  1. Referring to the code below, trace execution of the calls mystery(1) and mystery(13) using pencil and paper. In each case, create a table with a column for each of the variables count and n, and write down the new value of each variable at the end of the loop body, labeled (**) in the code.
def mystery(n):
    for count in range(100):
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
        if n == 1:
            return count
        # (**)

    return 100
  1. Given the code below, trace the execution of the call fibonacci(8). Again, create a table on paper showing the values of all variables when the end of the loop body is reached (at the comment labeled (**))
def fibonacci(n):
   previous = 0
   current = 1
   for count in range(n):
      print(current)
      temp = previous + current
      previous = current
      current = temp
      # (**)

Checkpoint 2

After tracing execution of the code above on paper, use pythontutor to step through the execution and make sure you were correct. Show the TA the tables you created on paper.

Part 3 - counting things

It is sometimes required that we keep a count of values in a program to perform any evaluation or further calculations

For Example: Below is a function to count how many numbers between 1 and n are divisible by 7

Checkpoint 3

  1. Write a function countP(s) that takes a string as parameter and returns the count of number of p’s that occur in the string s. (For example, countP("mississippi") should return 2.)

2. Write a function that simulates rolling a pair of dice 1000 times and counts how many times “doubles” occur (both numbers the same). Remember you can simulate rolling one die using random.randrange(1, 7)