Simplifying While Loops
00:00
While loops. Python has two different loop constructs, for
loops and while
loops. You typically use a for
loop when you need to iterate over a known sequence of elements. A while
loop, on the other hand, is used when you don’t know beforehand how many times you’ll need to loop.
00:22
In while
loops, you need to define and check the ending condition at the top of the loop. This will sometimes lead to some awkward code when you need to do some setup before performing the check.
00:35 Here’s a snippet from a multiple-choice quiz program that asks the user to answer a question with one of several valid answers.
01:38 This works but has an unfortunate repetition of identical input lines. It’s necessary to get at least one answer from the user before checking whether it’s valid or not.
01:48
You then have a second call to input()
inside the while
loop to ask for a second answer in case the original user answer wasn’t valid.
01:57
If you want to make your code more maintainable, it’s quite common to rewrite this kind of logic with a while True
loop. Instead of making the check part of the main while
statement, the check is performed later in the loop together with an explicit break
.
02:29
This has the advantage of avoiding repetition. However, the actual check is now harder to spot. Assignment expressions can often be used to simplify these kinds of loops. In this example, you can now put the check back together with while
where it makes more sense.
03:11
This while
statement is a bit denser, but the code now communicates the intent more clearly without repeated lines or seemingly infinite loops.
03:20
You can often simplify while
loops by using assignment expressions. The original PEP shows an example from the standard library that makes the same point. In the next section of the course, you’ll take a look at witnesses and counterexamples, which are elements which pass or fail specific checks, and you can see how the code for this can be simplified using the walrus operator.
Become a Member to join the conversation.