Python language basics 11: while loops

Introduction

In the previous post in this series we looked at if statements in Python. We saw how to set up conditions and tweak our actions accordingly. An if-block is only carried out if the boolean expression results in true.

However, what if we want to carry out an action as long as some condition is true and stop as soon as the condition is false? Consider the following sentences:

If the weather is nice then we’ll play football.

vs.

While the weather is nice we’ll be playing football.

The first sentence implies that we’ll start playing football if weather allows it but there’s nothing that says if and when we stop. The second sentence rectifies this situation. We’ll only play football while the weather is good.

This brings us conveniently to looping in Python using the ‘while’ keyword.

While loops

Like the if statement, the while statement also involves a boolean expression. The code block of the while statement will be executed over and over again as long as the condition is true. If the expression always results in true then we’re talking about an infinite loop. Consider the following example:

upperLimit = 10
counter = 0

while counter < upperLimit:
    print('We have not reached 10 yet!')
    counter += 1

That should be simple to follow. As long as the value of counter is less than the upper limit we execute the code block under the while statement. We need to increment the counter by one otherwise the loop will never exit as the counter will stay at value 0.

A short not aside: if you’re new to programming then the “counter += 1” bit may seem strange. It’s shorthand for “counter = counter + 1”.

It is possible to break out of a while loop early, i.e. before the boolean construct results in False, using the “break” keyword. The above example can be rewritten using a deliberate infinite loop:

upperLimit = 10
counter = 0

while True:
    print('We have not reached 10 yet!')
    counter += 1
    if counter == upperLimit:
        break

The boolean condition will always result in True of course, hence we’re deliberately starting an infinite loop. Within the loop we check whether the counter has reached the upper limit. If yes then we break the loop. This will cause code execution to continue at the first statement after the while loop. In the above case there’s no extra statement hence the program just finishes.

Read all Python-related posts on this blog here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Python language basics 11: while loops

  1. Brian Dead Rift Webb says:

    Reblogged this on Brian By Experience.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.