Salvatore Lopiparo

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:

>>> 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.

>>> apples = 0
>>> while apples < 3:
...     print("Before we add an apple:" + str(apples))
...     apples += 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!

>>> 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).

>>> 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 "", line 4, in 
KeyboardInterrupt

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

DROP A COMMENT

Your email address will not be published. Required fields are marked *