Python While Loops

The while loop is where you program a set of instructions to be carried out repeatedly for as many times as a given condition is true.

Python has two kinds of loops; a while loop, and a for loop. This page explains the while loop. We'll get to the for loop next.

In a way, while loops are kind of similar to if statements, in that they only do something if a certain condition is true. But the difference is, if the condition is true, an if statement will carry out the instructions once then continue on with the rest of the program. A while loop on the other hand, will repeat itself over and over again, until the condition becomes false. Therefore, a while loop needs to have something that changes each time it runs — otherwise it will run forever.

while loops are often used with a counter — an incrementing (or decrementing) number. Like this:

Result
1
2
3
4
5
6
7
8
9

Here's what the program is doing:

  1. Set a counter to 1
  2. Enter a while loop that keeps repeating while the number is less than 10
  3. Each time it repeats, print the counter value to the screen
  4. Increment the counter by 1

The bit where it increments the counter is a crucial part of this loop. If we didn't do that, the loop would continue on forever. The program would get stuck in an infinite loop (not a good thing).

Breaking a Loop

You can use the break statement to break out of a loop early.

Result
1
2
3
4

A Loop with else

Python lets you add an else part to your loops. This is similar to using else with an if statement. It lets you specify what to do when/if the loop condition becomes false.

Result
1
2
3
4
5
6
7
8
9
The loop has succesfully completed!

Note that the else doesn't execute if you break your loop:

Result
1
2
3
4

Positioning the Counter Increment

A common mistake that new programmers make is putting the counter increment in the wrong place. Of course, you can put it anywhere within your loop, however, bear in mind that its position can affect the output.

Here's what happens if we modify the previous example, so that the counter increments before we print its value:

Result
2
3
4
5

See how the output now starts at 2? This is because, on the loop's first iteration, we incremented the counter value before printing anything out.

Also note that the final number (5) is higher than the previous example.

The loop still outputs the same number of items (4), it's just that they've shifted by one increment.

Let's change the counter's initial value to zero:

Result
1
2
3
4
5

Now we end up with 5 items, starting at 1.

So you can see that it's important to understand how the counter's value at each stage of the loop can affect the end result.