Unit 1: Programming Basics

Lesson 5: For Loops

Notebook Authors

(fill in your two names here)

Team Roles

Facilitator: (fill in name)
Spokesperson: (fill in name)
Process Analyst: (fill in name)
Quality Control: (fill in name)

If there are only three people in your team, have one person serve as both spokesperson and process analyst for the rest of this activity.

At the end of this Lesson, you will be asked to record how long each Model required for your team. The Facilitator should keep track of time for your team.

Computational Focus: For Loops

Model 1: Lists of Numbers and Indexing

A variable can hold multiple items in the form of a list. Each item of the list is separated by a comma and sandwiched between square brackets [ ]. (Note: we actually already used a list in Lesson 3 to return multiple values from a function.) Each individual element of the list can be referenced by a unique index which is a numerical value that references sequential items in the list starting at 0.

This so-called "zero index" scheme is common in computer programming languages and can be counter intuitive. It means that you have to count starting at zero, like this - 0, 1, 2, 3, etc. For those of you with experience working with R it is indexed from 1, so this might take some adjustment.

Let's get going...

Type (don't copy and paste) the following code, one line per Jupyter cell, to observe the output (if any):

xlist = [2, 4, 1, 8]
print(xlist)
print(xlist[0])
print(xlist[3])
print(xlist[4])
xvalue = xlist[3]
print(xvalue) 
newlist = []
type(newlist)
print(newlist[0])

Critical Thinking Questions

1. What is the index number for the second element in xlist?

2. What is the value of the identifier xlist[2]?

3. In Model 1, explain the reason for the error when print(xlist[4]) is executed.

4. Write a statement that assigns the variable run to a list with three values.

5. Write a Python statement that reassigns the last element of run to a value of 100.

6. Write a Python statement that retrieves the first value of run and assigns it to an identifier named first.

7. Is it possible to have a list with no items, i.e. an empty list?

Model 2: The For Loop

A loop structure allows the programmer to execute statements multiple times in a program. A for-loop will execute the same block of code a specific number of times (usually determined by a list or range). Here is a diagram to illustrate a for loop:

Here is code for a simple for loop:
(Type the following code into a code cell below)

def model_two():  
    for i in [0, 1, 2]:
      print ("the number is", i)
    print ("goodbye")

To execute the code (known as a function call), type the function name and parentheses in another Jupyter code cell:

model_two()

Critical Thinking Questions

8a. How many times did the indented line of code execute after the for loop?

8b. How many times did the line of code NOT indented execute after the for loop?

9. Explain your answer to Question 8.

10. What is the value of i the first time the indented line of code executes?

11. Answer the parts of this question by copying and modifying the original code, running the modified code to illustrate in a Jupyter cell, and explaining in a markdown cell:

11a. Does the loop execute three times if the three numbers in the for loop list are non-consecutive?

11b. Does the loop execute three times if the three numbers in the for loop list are ordered in terms of decreasing value?

11c. Does the loop execute three times if the three numbers in the for loop list all have the same value?

12. What determines the value of the variable i? Explain your team's reasoning using grammatically correct English sentences.

13. Change the above for loop so the loop would execute five times. (code and md explanation)

14. Rewrite the for loop so that the loop executes zero times. (code and md explanation)

15a. Modify the model_two function so that it takes a single parameter – an identifier representing a list of numbers – then modify the for loop so that it uses the list represented by the identifier.

15b. Confirm that the function successfully executes the loop print statement five times if passed a list with five items in it.

15c. Describe one advantage of this new version of model_two in comparison to its original form.

Model 3: The range() function

The Python3 range function will generate a range object that functions in a for loop a lot like a list of numbers but isn't technically a list of numbers, it is a range object. Some of the details of this are not super important to use, but if you want more info, check out this link.

Let's explore the range function which can take in up to three numbers as arguments.

Type (don't copy and paste) the following code, one line per Jupyter cell, to observe the output (if any):

range(5)
list(range(5))
x = range(3)
x
print(x)
print(list(x))
list(range(5,10))
list(range(-3,4))
list(range(4,10,2))

Critical Thinking Questions

16. Explain the difference between the first two lines of code (range(5) vs list(range(5))).

17. If the argument of the range function has only a single number:
17a. What will be the first number in the generated list?

17b. What will be the last number in the generated list?

17c. How many numbers will there be in the generated list?

18. If the arguments of the range function includes two numbers:
18a. What will be the first number in the generated list?

18b. What will be the last number in the generated list?

18c. How many numbers will there be in the generated list?

19. If the arguments of the range function includes three numbers:
19a. What will be the first number in the generated list?

19b. What will be the last number in the generated list?

19c. What does the third argument represent?

19d. How many numbers will be in the list?

20. Write a statement that uses the range function to generate the list [0, 1, 2].

21a. Make a model_three function that is a modified version of the model_two function from above but it uses your answer to the previous question to control its for loop instead of a hard coded list of numbers.

22a. Now modify the model_three function so that it takes a single number as a parameter. Then modify the for loop statement so that the number of times the loop executes is determined by this parameter.

22b. Describe one advantage of this new version of model_three.

Examine the function below that approximates the square root by bisection search, called sqroot_bs().


In [3]:
def sqroot_bs(x):
    """
    takes a positive integer, approximates the square root, prints the approximation
    """
    numGuesses = 10  #number of attempts
    low = 0.0        #sets the low guess to zero, makes sense for square root
    high = x         #since we're dealing with square root, value of root is less than x
    guess = (high + low)/2.0     #bisection function where guess is estimated root, first set
    for i in range(numGuesses):  #loop that goes for numGuesses times, prints steps
        if guess**2 < x:  #if root estimate is less than actual root
            print('low = ' + str(low) + ', high = ' + str(high) + ', guess = ' + str(guess) + " - guess too low")
            low = guess   #low is assigned bisection result
        else:
            print('low = ' + str(low) + ', high = ' + str(high) + ', guess = ' + str(guess) + " - guess too high")
            high = guess          #if root estimate is greater than actual root, high is assigned bisection result
        guess = (high + low)/2.0  #bisection function to get new guess
    print(str(guess) + ' is close to the square root of ' + str(x))

Once you have looked through the code (which is heavily commented and includes an internal print statement to help explain bisection search), run the code cell above and the test case below.


In [ ]:
sqroot_bs(25)

23. Examine the printed output from running the sqroot_bs function.
23a. What is the initial guess for the square root of 25?

23b. List the next three guesses made by the program.

23c. How many guesses (including the initial guess) are calculated for the square root of 25 in the above code?

24. Explain in your own words how bisection search works using the sqroot_bs() function as an example.

25. Explain the following parts of sqroot_bs():
25a. The for loop.

25b. The if-else statement.

26. What do you predict would happen if you increased the value of the numGuesses variable in the function? Explain your thinking.

27. If you wanted to calculate the difference between the approximation and the real value of the square root, what would you do? (it's ok to either just describe or write code and describe)

Temporal Analysis Report

How much time did it require for your team to complete each Model?

END OF CLASS