Salvatore Lopiparo

Senior Software Engineer

Super Simple Python #8 – The while Loop

A while statement continues to do something until it meets some condition. The basic structure is:

While some condition is True, run some code.

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

The structure in Python should look familiar:

1
2
3
4
5
6
7
8
9
10
11
12
>>> bananas = 0
>>> while bananas < 5:
...     print("Adding a banana!")
...     bananas += 1  # Shorthand for bananas = bananas + 1
...     
Adding a banana!
Adding a banana!
Adding a banana!
Adding a banana!
Adding a banana!
>>> bananas
5

Python will run the entire code block if the condition is True, it will not stop in the middle.

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> apples = 0
>>> while apples < 3:
...     print("Before we add an apple:" + str(<span class="hiddenGrammarError" pre="while "><span class="hiddenGrammarError" pre="while "><span class="hiddenGrammarError" pre="while "><span class="hiddenGrammarError" pre="while "><span class="hiddenGrammarError" pre="while "><span class="hiddenGrammarError" pre="while ">apples))
...     apples</span></span></span></span></span></span> += 1
...     print("After we add an apple: " + str(apples))
Before we add an apple:0
After we add an apple: 1
Before we add an apple:1
After we add an apple: 2
Before we add an apple:2
After we add an apple: 3
>>> apples
3

If the condition is False from the start, the code block will be skipped entirely!

1
2
3
4
5
6
7
>>> grapes = 10
>>> while grapes < 5:
...     print("This code won't run!")
...     grapes += 500
...     
>>> grapes
10

Working with the while statement can be dangerous! You must closely inspect your code such that the condition will eventually be False. If the condition stays True, you will get an infinite loop and your code will never stop executing!

In case it does get into an infinite loop, here’s how to deal with it: Press Ctrl-C (That is, hold the Ctrl key and press the C key). This will cancel the Python Console from executing any more code by sending the KeyboardInterrupt exception to the interpreter. Let’s practice. Run the following code followed directly by pressing cancel (Ctrl-C).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> while True:
...     grapes += 1
...     print("Grapes!!! " + str(grapes))
...
Grapes!!! 1
Grapes!!! 2
Grapes!!! 3
# etc...
Grapes!!! 76422
Grapes!!! 76423
Grapes!!! 76424
Traceback (most recent call last):
  File "<console>", line 4, in <module>
KeyboardInterrupt

Now press Ctrl-C! My grapes got to 76424 before cancelling. You can see that it executes very fast!

Leave a Reply