Python 101 - More About Loops
A couple of weeks ago, you learned about for loops. But you didn’t learn about Python’s other type of loop, the while loop. You also didn’t learn about some other special looping keywords.
Today you will rectify those oversights! Here is what you will learn:
Create a
whileloopBreakout of a loop
Use
continueUse
elsewith loopsNest loops
Let’s get started!
Creating a while Loop
Python has one other type of looping construct that is called the while loop. A while loop is created with the keyword while followed by an expression. In other words, while loops will run until a specific condition fails, or is no longer truthy.
Let’s take a look at how these loops work:
This loop is formulated in much the same way as a conditional statement. You tell Python that you want the loop to run as long as the count is less than 10. Inside of the loop, you print out the current count and then you increment the count by one.
If you forgot to increment the count, the loop would run until you stop or terminate the Python process.
You can create an infinite loop by making that mistake or you could do something like this:
Since the expression is always True, this code will print out the string, “Program running”, forever or until you kill the process.
Breaking Out of a Loop
Sometimes you want to stop a loop early. For example, you might want to loop until you find something specific. A good use case would be looping over the lines in a text file and stopping when you find the first occurrence of a particular string.
To stop a loop early, you can use the keyword break:
In this example, you want the loop to stop when the count reaches 4. To make that happen, you add a conditional statement that checks if count equals 4. When it does, you print out that the count equals 4 and then use the break statement to break out of the loop. (Remember that the trailing “=” in f’{count=}’ requires Python 3.8; in earlier versions, you would need to write f’count={count}’.)
You can also use break in a for loop:
For this example, you want to break out of the loop when you find an apple. Otherwise you print out what fruit you have found. Since the apple is in the second tuple, you will never get to the third one.
When you use break, the loop will only break out of the innermost loop that the break statement is in -- an important thing to remember when you have nested loops!
You can use break to help control the flow of the program. In fact, conditional and looping statements are known as flow control statements.
Another loop flow control statement is continue. Let’s look at that next!
Using continue
The continue statement is used for continuing to the next iteration in the loop. You can use continue to skip over something.
Let’s write a loop that skips over even numbers:
In this code, you loop over a range of numbers starting at 2 and ending at 11. For each number in this range, you use the modulus operator, %, to get the remainder of the number divided by 2. If the remainder is zero, it’s an even number and you use the continue statement to continue to the next value in the sequence. This effectively skips even numbers so that you only print out the odd ones.
You can use clever conditional statements to skip over any number of things in a collection by using the continue statement.
Loops and the else Statement
A little known feature about Python loops is that you can add an else statement to them like you do with an if/else statement. The else statement only gets executed when no break statement occurs.
Another way to look at it is that the else statement only executes if the loop completes successfully.
The primary use case for the else statement in a loop is for searching for an item in a collection. You could use the else statement to raise an exception if the item was not found, or create the missing item, or whatever is appropriate for your use-case.
Let’s look at a quick example:
This example loops over a list of three integers. It looks for the number 4 and will break out of the loop if it is found. If that number is not found, then the else statement will execute and let you know.
Try adding the number 4 to the list and then re-run the code:
A more proper way of communicating an error would be to raise an exception to signal the absence of the number 4 rather than printing a message. You will learn how to do that in chapter 14.
Nesting Loops
Loops can also be nested inside of each other. There are many reasons to nest loops. One of the most common reasons is to unravel a nested data structure.
Let’s use a nested list for your example:
The outer loop will extract each nested list and print it out as well. Then in the inner loop, your code will extract each item within the nested list and print it out.
If you run this code, you should see output that looks like this:
This type of code is especially useful when the nested lists are of varying lengths. You may need to do extra processing on the lists that have extra data or not enough data in them, for example.
Wrapping Up
Today you learned more about Python loops.
Specifically, you learned about the following topics:
Creating a
whileloopBreaking out of a loop
Using
continueLoops and the
elsestatementNesting loops
At this point, if you combine what you learned here with the for loop article, you will have an excellent foundation for using loops in any of your programs.
Start practicing, and you’ll be able to use loops confidently. Have fun!










