Unit 1: Programming Basics

Lesson 6: while loops

Notebook Authors

(fill in your two names here)

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 group, 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: while loops

Model 1: Useful Reassignments

Consider the following series of Python statements. At the end of each section of code, identify the current value of the specified variable(s) (i.e., the value displayed if you used the print command) assuming all previous lines of code were executed. Do not run this code in a Python code cell yet.

Section1

x = 1
y = 2    
y = x  
x = y

Value of x =
Value of y =

Section2

x = 1
y = 2    
z = y  
y = x
x = z

Value of x =
Value of y =

Section3

z = 2
x = 2
z = z + 1
z = z + 1
x = x + z
a = a + 1

Value of z =
Value of x =
Value of a =

Section4

a = list(range(3))
i = 1
a[0] = a[0] + i  
a[i] = a[0] + 1  
a[i+1] = a[i-1] + 1

Value of a =

Critical Thinking Questions

1. Execute all of the code from above in cells below (best as one cell per section) and check that the results coincide with the predictions of your group.
Discuss the resolution of any difference below.


In [ ]:

2. Explain why the value of x is not 2 after Section1 of the code.

3. Describe what happens to the values of the variables x and y in Section2 of the code.

4. What is the purpose of the variable z in Section2 of the code? Explain.

5. Describe what happens to the value of z in Section3 of the code.

6. Why is it possible to increment (change the value of a variable by one) the variable z but not the variable a in Section3 of the code?

7. Describe how the first two assignment statements in Section4 of the code differ significantly from last three assignment statements in Section4 of the code?

8a. Write an assignment statement that sets the value of the last element of the list, a, in Section4 to 3 using only current elements of the list, a, referenced appropriately in terms of index i.

8b. Why do you need the range(3) enclosed in list()? Also use Python code to illustrate.

Model 2: while loops

Another common looping structure is a while-loop. Examine the diagram below:

Here is an example while loop:

def model_two():
    i = 0
    while i < 3:
       print ("the number is", i)
       i = i+1
    print ("goodbye")

Type the code for model_two() into a code cell.

Then call the model_two() function in a second code cell to make sure it works.


In [ ]:


In [ ]:

Critical Thinking Questions

9. What must be the value of the Boolean expression (after while) in order for the first print statement to execute?

10. What is the increment statement for the variable i in the above code?

11. What happens to the value of the variable i during the execution of the loop?

12. Explain why the indented code does not execute after the code prints “the number is 2”.

13. Reverse the order of the code in the body of the while-loop in the model_two function like this:

while i < 3:
    i = i+1
    print ("the number is", i)

13a. How does the order impact the displayed message corresponding to the last indented print line inside the while-loop?

13b. Does the order impact the number of print lines that display?

14. Identify three different ways to modify the code so that the loop only executes twice. Illustrate each in code and include a brief explanation.

15. Describe the three parts of the while loop that control the number of times a while-loop executes.

Warning: Read this section! question 16 will and question 17 can create an infinite loop.
Be prepared! Infinite loops can crash your notebook, notebook server, and/or web browser!
The fastest way to kill an infinite loop is to use the keyboard shortcut I,I (press the I key on yoru keyboard 2 times in rapid succession while the cell is in command mode). This can also be accomplished by going to the Kernel --> Interrupt menu option as fast as possible.

Before you run any suspect while loop save your notebook! If you have produced an infinite loop, the safest way back to productivity is to use the Kernel --> Restart & Clear Output menu option as this will both restart the kernel and flush any obnoxiously long output from an infinite print.

16. Warning infinite loop coming! Copy the model_two() function, comment out the increment statement for the variable i, and execute the new version of the model_two() function. Interrupt the kernel ASAP. Describe the behavior you see, and explain why it happened.

17. Forgetting to increment your counting variable is not the only mistake that will create an infinite loop. Restore the increment statement in the model_two() function. What is another error you could introduce to the model2 function that would still cause an infinite loop? (depending on your experience so far, might be best to describe but NOT run code)

Model 3: while loops in practice

When writing a loop, it's helpful to answer a few questions before you start coding:

  • what condition must be true for the loop to repeat?
  • what needs to be initialized before the start of the loop?
  • what will change inside the body of the loop so that the loop will eventually end?

Critical Thinking Questions

18. In this model, you will design a sum function that prompts the user for multiple numbers and returns the sum of all these values. The sum function should take a single parameter (the number of times your program should prompt for values to be entered). Be sure to call your function with at least the following test case:

sum(5)

and you should be able to enter the following 5 values, e.g., 10, 2, 30, 4, 5. The function should return the result of 51.

Begin by answering the following questions (NOT coding):

18a. Describe in English the Boolean expression that must be true for the loop to repeat.

18b. What variables (used by the Boolean expression) need to be initialized before the start of the loop?

18c. Describe in English what will need to change inside the body of the loop so that the loop will eventually end.

18d. Now list what else needs to happen inside the body of the loop for you to calculate the sum of multiple numbers.

18e. Given your answer to 18d, are there any other values that need to be initialized before the start of the loop?

19. This function could be written several different ways. To help you gain experience with while-loops, you should write this function using a while loop and without using a list. Your program needs to track the running total of all the numbers being entered, yet at all times, it will only be able to access the current number inside the loop. Fill out the rest of this table which tracks the running total of the function:

value entered running total
10 10
2
30
4
5

20. Once you have answered the above questions, you are ready to code our sum function here!


In [ ]:

Temporal Analysis Report

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

Model 1:

Model 2:

Model 3: