Skip to main content

Section 5.12 Group Work - Loops (For, Range, While)

It is best to use a POGIL (Process Oriented Guided Inquiry Learning) approach with the following. In POGIL, students work in groups on activities and each member has an assigned role. For more information see https://cspogil.org/Home 1 .

Note 5.12.1.

If you work in a group, have only one member of the group fill in the answers on this page. You will be able to share your answers with the group at the bottom of the page.
A loop allows you to execute the same statements multiple times. Python has two kinds of loop structures: for loops, which iterate over the items of a sequence, and while loops, which continue to execute as long as a condition is true.
Content Learning Objectives: After completing this activity, you should be able to:
  • Explain the syntax and the purpose of a for statement.
  • Predict how range() works given 1, 2, or 3 arguments.
  • Identify the three main components of a while loop.
Process Skill Goals:
During the activity, you should make progress toward:
  • Tracing the execution of while/for loops and predict their final output (Critical Thinking).

Subsection 5.12.1 for Statements

A for loop executes the same block of code “for each item in a sequence.”

Checkpoint 5.12.2.

Run this code to see what it prints.

Checkpoint 5.12.3.

    Q-2: How many times does the indented line of code execute under the for loop?
  • 0
  • Incorrect! Remember, the body of a for loop executes as many times as there are items in a sequence. Try again.
  • 1
  • Incorrect! Remember, the body of a for loop executes as many times as there are items in a sequence. Try again.
  • 2
  • Incorrect! Remember, the body of a for loop executes as many times as there are items in a sequence. Try again.
  • 3
  • Correct! There are three items in the sequence [2, 7, 1], so the body of the for loop executes 3 times.
  • 4
  • Incorrect! The question is asking only about the indented line of code under the for loop, so line 4 does not count. Try again.

Checkpoint 5.12.4.

    Q-3: How many times does the line of code NOT indented execute after the for loop?
  • 0
  • Incorrect! After the for loop terminates (finishes executing), the program continues to execute the non-indented lines of code beneath it. Try again.
  • 1
  • Correct! The non-indented line of code executes only once, as it is not part of the for loop and therefore does not execute multiple times.
  • 2
  • Incorrect! The absence of an indent in Line 4 means that it is not part of the for loop. Try again.
  • 3
  • Incorrect! The absence of an indent in Line 4 means that it is not part of the for loop. Try again.
  • 4
  • Incorrect! The absence of an indent in Line 4 means that it is not part of the for loop. Try again.

Checkpoint 5.12.5.

Checkpoint 5.12.6.

In general, the length of the list determines the number of times that the loop repeats. The value of the variable x is selected from the list. Each time the loop runs, the next value from the list is assigned to x.
Before your for statement, you can assign your list to a variable and your program will run the same way:

Checkpoint 5.12.7.

Run this code to see what it prints.

Subsection 5.12.2 The range Function

The Python range function will generate a sequence of numbers. The range function can take up to three numbers as arguments.

Checkpoint 5.12.8.

Run this code to see what it prints.
The second line of output describes the range as a function, whereas the second line shows the actual range of values as a list by using the list function.
If the argument of the range function specifies a single number, like range(x), the first number listed will be 0, the last number listed will be x - 1, and there will be x numbers in the list.

Checkpoint 5.12.9.

Q-9: Use the range function with one parameter to generate the sequence 0, 1, 2, 3.
If the argument of the range function specifies two numbers, like range(x, y), the first number listed will be x, the last number listed will be y - 1, and there will be y - x numbers in the list.

Checkpoint 5.12.10.

Q-10: Use the range function with two parameters to generate the sequence 1, 2, 3, 4.
If the argument of the range function specifies three numbers, like range(x, y, z), the first number listed will still be x, just like the two parameter version. The third argument represents how much to increment the number by each time. The sequence will generate numbers up to, but not including, y. To calculate how many numbers will be in the list, take the result of (y - x) / z and round it up to the nearest whole number.

Checkpoint 5.12.11.

Q-11: Use the range function with three parameters to generate the sequence 1, 3, 5, 7.

Checkpoint 5.12.12.

    Q-12: If you wanted to execute a loop 100 times, which type of for statement is the most appropriate to use?
  • for i in range(x)
  • Correct! This is the simplest way to write it and makes your code easiest to read.
  • for i in range(x, y)
  • Incorrect! Although this could work, it can be done more simply. Try again.
  • for i in range(x, y, z)
  • Incorrect! Although this could work, it can be done more simply. Try again.
  • for i in list
  • Incorrect! You don’t have a preexisting list, so you should use the range function to generate one for you. Try again.

Checkpoint 5.12.13.

    Q-13: If you wanted to use each item of an existing list named numbers inside the loop, which type of for statement should you use?
  • for i in range(x)
  • Incorrect! The list exists already, so there is no need to generate one using the range function. Try again.
  • for i in range(x, y)
  • Incorrect! The list exists already, so there is no need to generate one using the range function. Try again.
  • for i in range(x, y, z)
  • Incorrect! The list exists already, so there is no need to generate one using the range function. Try again.
  • for i in numbers
  • Correct! Because your list exists already, you can use this format to iterate through each item inside it.

Subsection 5.12.3 while Statements

A more general looping structure is the while statement.

Checkpoint 5.12.14.

Run this code to observe the behavior of a basic while loop and answer the questions that follow.

Checkpoint 5.12.15.

    Q-16: What must the value of the Boolean expression (after the while) be in order for the first print statement to execute?
  • True
  • Correct! The body of the while loop will execute as long as the loop condition is True.
  • False
  • Incorrect! You’ve got it backwards. Try again.
In the above code, the variable i is incremented by 1 each time the loop body is executed. Because the value of i steadily grows, the “loop condition” (the Boolean expression after the while) eventually becomes False when i becomes 3, which causes the loop body to stop executing.

Checkpoint 5.12.16.

    Q-17: Imagine that lines 3 and 4 in the above code were swapped. What is the new output of this new code?
    i = 0
    while i < 3:
        i = i + 1
        print(i)
    print("goodbye")
    
  • 0 1 2
  • Incorrect! This is what it printed before, but swapping the lines would change the output. Try again.
  • 1 2 3
  • Correct! i is incremented before it is printed, so the numbers it prints are one higher than before.
  • 0 1 2 3
  • Incorrect! The loop still terminates when the end of the loop body is reached (when i < 3 is False). Try again.
  • 1 2 3 4
  • Incorrect! The loop still terminates when the end of the loop body is reached (when i < 3 is False). Try again.
  • There would be no output
  • Incorrect! Something would still be printed. Try again.

Checkpoint 5.12.17.

    Q-18: Which of these modifications would make the loop in the original code only run twice? There are one or more answers.
    Here is the original code again:
    i = 0
    while i < 3:
        print(i)
        i = i + 1
    print("goodbye")
    
  • Change line 1 to i = 1
  • Correct! This would print 1 2.
  • Change the loop condition to i < 2
  • Correct! This would print 0 1.
  • Change line 4 to i = i + 2
  • Correct! This would print 0 2.
  • Swap lines 1 and 2
  • Incorrect! This would cause a NameError because i wouldn’t be defined when the program tries to run the while line for the first time. Try again.
A while loop has three parts that control the number of times it executes. The first part initializes the variable or condition, the second part tests whether the end has been reached, and the third part updates the variable or condition.

Checkpoint 5.12.18.

    Q-19: If you deleted line 4 of the code above, what would print?
  • 0 1 2
  • Incorrect! i does not increase anywhere in the code. Try again.
  • 1 2 3
  • Incorrect! i begins at 0, not 1. Try again.
  • 0 would print infinitely
  • Correct! Because the value of i never changes, the program will never leave the while loop.
  • SyntaxError
  • Incorrect! The compiler can interpret your code, but it may not do what you intended. Try again.
When writing a while loop, it’s helpful to answer a few questions before you start:
  • What needs to be initialized before the loop?
  • What condition must be true for the loop to repeat?
  • What will change so that the loop eventually ends?
For example, consider the code below. The code prompts the user for n numbers and returns the sum of these values. For example, when n = 5, the user is asked to input five numbers. If the user inputs 30, 10, 50, 20, and 40, the function would return the value 150.

Checkpoint 5.12.19.

Observe the behavior of this code to see how it answers the the three bullet points above.
Before the loop begins, the i variable, which counts how many times the loop runs, must be initialized. However, the total variable must also be initialized outside of the while loop, or else it would reset to 0 each time the loop ran.
The loop repeats n times, so the Boolean expression that must be true for the loop to continue is i < n.
Finally, for the loop to eventually end, i must be incremented, so we include the statement i = i + 1.
Making sure you answer these questions helps you write better (and less buggy) while loops.
https://cspogil.org/Home