Exploring While Loops in Python
In this course, we explore While loops in more depth. This course is part of a series of content designed to help you learn to program with the Python programming language.
- Explain the purpose of a while loop
- Describe how to stop a while loop
This course was designed for first-time developers wanting to learn Python.
This is an introductory course and doesn’t require any prior programming knowledge.
Hello, and welcome! My name is Ben Lambert, and I’ll be your instructor for this course. This course is part of a series of content designed to help you learn to program with the Python programming language. Should you wish to ask me a specific question, you can do that with the contact details on screen. You can also reach support by using the email address: email@example.com. And one of our cloud experts will reply.
In this lesson we’re going to explore while loops more in-depth. Loops are used to repeat actions. While loops in particular are designed to repeat an action while a condition evaluates to True. Recall that Python includes an object type referred to as a boolean. Boolean values can be in one of two states, True or False. Booleans are an important concept for programmers. Because they enable us to make decisions and control the flow of our code.
We’ve seen this with the if-family of keywords in other lessons. The if statement enables us to determine which lines of code the interpreter reads. When the if statement evaluates to True that block of code is run. The while loop functions much the same. While some condition is True, repeat the block of code.
While loops are used to repeat a task an unknown number of times. For example, a video game engine might render some graphics while the game is running. As soon as the condition changes from True to False, the loop stops. The syntax for a while statement starts with the keyword while and ends with a colon and newline. In between the word while and the colon is where we include the condition used to control this loop.
The condition can be anything that produces a boolean object. Check out this example where we bind the name keep_running to True. Then using a while loop we repeat this code for as long as this name is bound to True. If it becomes False, this code will stop. We’re using the built-in input function to enable us to free-type something to compare against in these if statements.
First we compare the entered input with the string “stop.” If we enter the word stop, this code block will be run. This will bind keep_running to False. Which means as soon as the loop repeats and Python checks the keep_running binding, it’ll see that it’s now False and stop.
Running this we can enter the command greeting. And it prints hey. If we enter the text: stop it should stop the loop. And since there isn’t any code after it, the application will stop. In this case, our condition for the while loop is an individual name binding. Let’s see a slightly more complex condition by using some operators.
Let’s bind two names to boolean objects. This while loop is going to continue running while the name keep_running is bound to True and the name need_restart is not True. The not operator flips a boolean value to its opposite state. If it’s True, it becomes False. If False, it becomes True. The and operator determines if the conditions on both sides evaluate to True. This condition is a bit more complex than what we’ve seen so far. Don’t worry if this doesn’t fully resonate with you just yet. We’ll cover boolean logic in later content.
For now, know that just like the if statement the while loop doesn’t care how we produce our boolean decision. We can use multiple operators, functions, name bindings, and whatever other means of producing a boolean provided by Python.
Once our code flows into a while loop it’s trapped there until the loop is broken. Python provides a couple keywords which we can use inside of a loop to control its flow. The break keyword is used to instruct the interpreter to break the current loop. The continue keyword is used to instruct the interpreter to go back to the top of the loop and re-evaluate the condition. This can be useful when you don’t want the interpreter to run through the code that follows the continue keyword.
Here’s an example: This while loop is specifically set to True. This results in an infinite loop because once this code is running, we can’t change this value of True. This means we need to break this loop for ourselves.
Using the input functions we can enter some text. When we enter: stop the interpreter will read this line and break out of the loop. When we enter: skip the interpreter will read this line and immediately go back to the top of the loop and re-evaluate the condition. Which we’ve explicitly set to True. If we enter anything else, or nothing at all, then neither of these lines will be run. Which means this print function will run and display this string.
Running this we can see that we’re prompted with our angle bracket. So we’re inside the loop, and running this line here. Let’s just hit enter or return so that neither of these conditions are True; and now we can see our message displayed.
Now we’re back to the top of the loop and we’re prompted again to enter something. If we were to type skip the interpreter is going to read this instruction to continue and it will immediately go to the top of the loop. Because this line with the continue keyword is above the print function if we enter skip we shouldn’t see this printed message. Notice we’re prompted to enter a command, but no message is displayed.
The break keyword immediately stops the current loop. When I enter stop notice the application stops. No print message, no prompt. The loop is complete. Okay, let’s put this new knowledge to practice. Previously we created a guessing game which allowed a user to guess a number between one and ten. And while it worked, it had to be restarted after every incorrect guess.
Let’s review how a while loop changes that code. Using a while loop will enable us to prompt the user for a guess until they get it correct. The code on the left is the original. The code on the right is the updated version. They’re similar. However, the updated version uses an infinite loop to keep prompting the user. If the guess and answer match the built-in print function returns a message. Then it breaks out of the loop. Otherwise, it displays the message: guess again and the loop repeats.
Playing this version is a better user experience because the user doesn’t need to restart the application for each new guess. While loops are useful in cases where something needs to be repeated until some boolean condition is met.
And just like if-statements, loops can be nested. Loops can run inside of other loops. There are use cases for nesting loops. And you’ll learn about those over time. For now, just know that while loops can be nested. Which does require some extra attention from us as developers.
If we’re not mindful of breaking loops we could head down a series of infinitely looping rabbit holes. Wherein the flow of our code will be forever stuck. Imagine being stuck in a thought-loop forever...forever...forever…
Okay, this seems like a natural stopping point. Here are your key takeaways for this lesson:
- The purpose of a while loop is to repeat an action until some condition is met.
- The condition consists of any expression which evaluates to True.
- The keyword continue is used to jump to the top of the loop and re-evaluate the condition.
- The keyword break is used to stop the current loop.
Alright, that's all for this lesson. Thanks so much for watching. And I’ll see you in another lesson!
Ben Lambert is a software engineer and was previously the lead author for DevOps and Microsoft Azure training content at Cloud Academy. His courses and learning paths covered Cloud Ecosystem technologies such as DC/OS, configuration management tools, and containers. As a software engineer, Ben’s experience includes building highly available web and mobile apps. When he’s not building software, he’s hiking, camping, or creating video games.