Simplifying While Loops
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.
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.
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
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.
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.