Loops

Loops let us do operations on multiple items. There are two popular kinds of loops in Python: for loops and while loops. In this chapter, you will use for loops and while loops to work with lists and to control program flow.

Learning Objectives

You should be able to:

  • Describe the usefulness of loops
  • Use for loops
  • Use while loops
  • Use break to exit loops

Video Walkthrough

Use this video to follow along with the steps in this lab.

For Loops

Python's for loops are good for iterating through list items.

  • Create a file called for.py and add the following code.
names = ["Alice", "Bob", "Eve"]
for name in names:
    print("Hello " + name)
  • Important: There should be 4 spaces before the print function.
  • Line 1 creates a list of strings.
  • Line 2 contains the code that starts the loop. The for keyword tells Python that we want a loop. We know that the names variable was created on line 1. The name variable is new in this program. The name variable temporarily holds the current name from the names variable. So the first time through the loop, the name variable will have the name, "Alice." The second time through the loop, the name variable will have the value "Bob." The value of the name variable will be updated for every item in the names list. At the end of line 2 is a colon (":") that tells Python that everything that comes after is what should happen inside the loop.
  • Line 3 starts with 4 spaces. Python uses spaces (or tabs) for defining the structure of code. Other programming languages often rely on curly braces ("{ }") for defining the structure of code. Some say that Python's use of spaces rather than curly braces makes it easier to read. Problems can occur when spaces and tabs are mixed, or you forget to add spaces and Python yells at you and hurts your feelings, and then you have to hunt through your source code trying to find where you need to add a space, or where you need to delete a tab and add four spaces.
  • Save and run the code.

You should see the output:

Hello Alice
Hello Bob
Hello Eve

For Loop Challenge

  • Create a file called for_nums.py.
  • In the first line, create a list of integers.
  • In the second line, start the for loop.
  • In the third line, be sure to indent 4 spaces, then print the numbers.

There do not need to be any quotation marks in your loop.

While Loops

In Python, while will continue until some condition is met, then the loop is exited.

  • Create a file called while.py with the following code.
counter = 1
while counter < 10:
    print(counter)
    counter = counter + 1
print("Done")
  • Line 1 creates an integer variable named counter with a value of 1. Note that this variable is created outside of the loop.
  • Line 2 starts the while loop. This statement tells Python to run the indented code below as long as the counter variable is less than 10. If the counter variable is not less than 10, the code will continue after the loop.
  • Line 3 prints the current value of the counter variable.
  • Line 4 adds one to the counter. If this line were omitted, the loop would continue forever.
  • Line 5 will print "Done" after the while loop has exited.
  • Save the file and run the program. You should see the output:
1
2
3
4
5
6
7
8
9
Done

While Loop Challenge

  • Create a file called while_launch.py to create a launch countdown counting from 10 down to 1, then printing "Blastoff!".
  • Your launch countdown should look like this:
10
9
8
7
6
5
4
3
2
1
Blastoff!
  • The numbers 10 through 1 should be printed in a while loop.

Breaking Out of Loops

There are many cases when it is necessary to exit a loop. The break keyword is used to make your code jump out of a loop. The following code will demonstrate how to exit from a loop using break.

  • Create a file called break.py with the following code
names = ['Alice', 'Bob', 'Eve']
for name in names:
    print(name)
  • Save and run the code. It should print the three names.
  • Modify the code so that the loop exits if it finds the name "Bob."
names = ["Alice", "Bob", "Eve"]
for name in names:
    if name == "Bob":
        break
    print(name)
  • Save and run the code.
  • Notice that only "Alice" is printed. When the loop got to "Bob," the code exited and therefore the remaining names were not printed.
  • The break keyword can be used in while loops, also.
  • Create a file called repeat.py with the following contents.
answer = input("Guess my favorite color: ")
while True:
    if answer.lower()=="blue":
        print("Correct!")
        break
    else:
        answer = input("Nope! Guess again: ")
  • Run the code. Enter a few different colors, and finally "blue."
  • Notice that the while loop could theoretically run forever. The only way the loop will ever exit is when the break is triggered.

Challenge

  • Create a while loop that never exits. Run it. What happens to your program? (Hint: press control+c to exit.)
  • Modify the code to exit on a specific condition using the break keyword.

Reflection

  • When would it be better to use while loops and for loops?
  • When would it be appropriate to include an infinite loop in your code?

Key Terms

  • For Loop: A control flow statement that repeatedly executes a block of code for each item in a sequence (such as a list, tuple, or range). In Python, a for loop iterates over the elements of a sequence, allowing you to perform operations on each element.
  • While Loop: A control flow statement that repeatedly executes a block of code as long as a specified condition is True. In Python, a while loop continues to execute the code block until the condition evaluates to False.