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
forloops - Use
whileloops - Use
breakto 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.pyand add the following code.
names = ["Alice", "Bob", "Eve"]
for name in names:
print("Hello " + name)
- Important: There should be 4 spaces before the
printfunction. - Line 1 creates a list of strings.
- Line 2 contains the code that starts the loop. The
forkeyword tells Python that we want a loop. We know that thenamesvariable was created on line 1. Thenamevariable is new in this program. Thenamevariable temporarily holds the current name from thenamesvariable. So the first time through the loop, thenamevariable will have the name, "Alice." The second time through the loop, thenamevariable will have the value "Bob." The value of thenamevariable will be updated for every item in thenameslist. 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
forloop. - 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.pywith 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
whileloop. This statement tells Python to run the indented code below as long as thecountervariable is less than 10. If thecountervariable is not less than 10, the code will continue after the loop. - Line 3 prints the current value of the
countervariable. - Line 4 adds one to the counter. If this line were omitted, the loop would continue forever.
- Line 5 will print "Done" after the
whileloop 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.pyto 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
whileloop.
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.pywith 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
breakkeyword can be used inwhileloops, also. - Create a file called
repeat.pywith 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
whileloop could theoretically run forever. The only way the loop will ever exit is when thebreakis triggered.
Challenge
- Create a
whileloop that never exits. Run it. What happens to your program? (Hint: presscontrol+cto exit.) - Modify the code to exit on a specific condition using the
breakkeyword.
Reflection
- When would it be better to use while
loopsandforloops? - 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
forloop 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 toFalse.