The while loop can be found in most programming languages. Although its exact function differs from language to language, it is mostly used to perform an action provided certain conditions are met. The while loop is used extensively in Python and alone with for and if-else loops, forms the basis of manipulating data in the language.
In this tutorial, we will learn the basics of using the while loop in Python. We will look at the basic syntax and the many uses of while loop. We will also create a number of simple programs to understand how this loop works in Python.
To learn more about the while loop and other advanced Python topics, check out this ultimate Python programming tutorial.
Understanding the While Loop
The while loop is easy enough to understand in plain English: it keeps on executing a piece of code as long as a particular condition is true.
Imagine that you work in the HR department of a big Fortune 500 firm. One of your senior managers is due to retire in the next two months. This manager performs a vital role in the company and it is crucial that you find a suitable replacement as soon as possible. So you put out wanted ads across the internet and schedule interviews for hundreds of candidates. Essentially, you will keep on interviewing candidates until you find someone good enough to replace the outgoing manager.
If you wanted to, you could represent your situation as follows:
while job opening = open: interview candidates
If you were so inclined, you could also write this in the form of an ‘if-else’ statement (which we’ve already covered before here):
if job opening = open: interview candidates else: do not interview candidates
This is the essence of the while loop: do something as long as a condition holds true.
Syntactically, the while loop is written as follows:
while condition1: do_something
Two things to note here:
- There must be a colon (:) at the end of the while statement.
- The action to be performed must be indented by four spaces (or one press of Tab).
Let’s look at an example to understand how the while loop works:
Let’s say you want to print all the numbers from one to ten. You can use the for loop for it, but it’s far easier to use the while loop, as shown below:
#Creating a variable to start the count count = 0 #Creating while loop while count < 6: print count count += 1
If you run this program, this is what you should see:
What’s going on here? Let’s break it down:
count = 0
This is a variable we created to start our count. If you wanted to start counting from 10, you would give it the value of count = 10.
while count < 6
This is the start of the while loop. It basically tells Python to perform the following actions as long as count remains less than six. As soon as count reaches six, the while loop should stop as that would make the condition False.
count += 1
This is a popular shorthand for count = count + 1. Since we want to list the numbers from 0 to 6 (not including six), we will increase the count by one every time Python goes through the loop. If you wanted the count to increase by two, you would write count = count + 2.
New to Python? Check out this course on Python for beginners to get started!
In the above example, what would happen if the condition (count < 6) is never fulfilled, i.e. count never reaches six?
Try out the following: remove the count += 1 line from the above example and run the program again. You should see a stream of never ending zeros.
This, ladies and gentlemen, is what we call an ‘infinite loop’. To escape it, just hit CTRL-C (or quit Powershell altogether).
While loops are notorious for this particular problem. Basically, the condition used in the while loop must become eventually false for the loop to work. By removing the count += 1 line, we made sure that count remained 0 and never increased to 6 (after which the loop would become False).
You must be very careful when using while loops since there’s always the possibility of using an incorrect condition and setting off an infinite loop. This would cause your program to crash and you would either have to close it altogether, or force-quit the loop.
Nested While Loops
We learned in our previous tutorials on if-else and for loops that we can nest loops inside each other. This is also true for while loops where we can create multiple levels of while statements as long as proper indentation rules are followed.
The syntax is as follows:
while condition1: do_something while condition2: do_something while condition3: do_something
Let’s look at an example to understand nested while loops.
Let’s say you have two numbers: -20 and 20. You want to compare these numbers and increase the negative number’s count so that it is the same as the positive number’s. This is easy enough with the while loop, as we learned above:
x = -20 y = 20 while x <= y: print “X is now: “, x x = x + 1
This will simply increase x by 1 until it is the same as y (i.e. 20), as shown below:
But what if we Python to also print “X is negative” as long as x is less than 0? To do this, we can simply use another while loop, like this:
x = -20 y = 20 while x <= y: print “X is now: “, x x = x + 1 while x <= 0: print “X is negative” x = x + 1
The result will look like this:
Thus, Python will print the count only once X is more than 0.
While and Else
Just like for loops, you can include an else conditional statement without the corresponding if statement in while loops as well.
The basic syntax looks as follows:
while condition1: do_something else: do_something_else
This works quite like an if-else statement. It basically instructs Python to do something while condition1 is true. When it is not true, do something else, as directed under the else statement.
As before, let’s look at an example to understand how this works.
Let’s say you want to write the first ten numbers as in example 1 above. But for the final number (i.e. 10), you want to write “The final count is: “.
We can do this by using an else statement with while as shown below:
count = 0 while count < 10: print “The current count is: “, count count += 1 else: print “The final count is: “, count
You should see the following output upon running the program:
This was a fairly basic example. The else statement can accommodate complex operations, including nested loops, if-else statements, etc.
While Loops and Lists
If you followed our earlier for loop tutorial, you know that loops are used extensively with lists. In some ways, the while loop behaves like the for loop, extracting individual elements from the list and performing operations on them.
The best way to understand this, of course, is with an example.
Let’s say we have a list of names. We want to print out individual items on the list on separate lines. You know this is pretty easy to do with a for loop as shown below:
names = [‘John’, ‘Jerome’, ‘Paul’, ‘George’, ‘Andy’, ‘Michael’] for name in names: print name
This will yield us the desired result:
However, to use a while loop to print list items individually, we need to count the list index and increase it by one step.
It’s far clearer in code than in words:
#Creating a list of names names = ['John', 'Jerome', 'Paul', 'George', 'Andy', 'Michael'] #Creating the variable that will hold our count i = 0 #Creating the while loop while i < len(names): #len(names) is used to check length of names list print names[i] #Prints out the names list with i as index i += 1 #Increases i so that subsequent items in list can be printed
This yields the same result as before:
What we’re doing here can be explained as follows:
- To print individual items from a list, we need the list index. names will print the second item on the list, for instance, while names will print the fourth (remember that list index count always starts from 0).
- Since we want to print all items on separate lines, we need a way to increase the list index in our print statement. Hence, we create the variable i with an initial count of 0.
- We want to make sure that our index count remains the same as the length of the list. Hence, we used len(names) in the while loop. Can you explain why we used < and not <= in the condition?
- To print individual items, we used print names[i].
- To increase index count, we added an i += 1 statement.
Obviously, this is way more complicated than using a for loop. It’s a prime example of how using the wrong kind of loop can make your work far more tedious than it should be. The next time you have to perform a similar operation, resist the urge to use the while loop and use a for loop instead.
Nonetheless, the while loop does make it easy to manipulate lists in certain situations. Let’s see how this works with another example:
In this example, we’ll build our own list of countries we’ve traveled to. We’ll collect raw input from the user and use and if-statement to verify input, as can be seen in the code below:
#Creating empty list countries =  #Creating variable that will control number of countries we can enter count = 0 #Creating the while loop while count < 5: #This ensures that only five countries can be entered print "Please enter a country you've been to" next = raw_input("> ") #If conditional statement to verify input if len(next) > 0 and next.isalpha(): countries.append(next) count = count + 1 else: print "I'm sorry, but I can't accept that input" print countries
When run, the program will give the following output:
If you enter a number or don’t enter any input at all, you’ll see the following:
The program is pretty self-explanatory but there are a few things you should pay attention to:
- len(next) > 0 is used to check whether you’ve entered any input or not. If the length is 0, the program will ask for input again.
- next.isalpha() utilizes a built-in Python function, isalpha(), to make sure that the user can only enter alphabets, not numbers.
- countries.append(next) uses .append(), the default Python function for adding items to a list.
This covers the basics of while loops for now. There is a lot more to learn in Python, including working with dictionaries, creating classes and objects, and understanding Python’s many, many built-in functions. Check out this course to learn more advanced topics in Python.
Before we leave, try out a few homework exercises to polish your while loop knowledge.
- In Example 2, remove the second while loop and use a nested if-else statement instead to achieve the same results.
- In Example 4, try creating two additional lists and printing out their content.
- In Example 5, add another while loop to print each country on separate lines.
- Head over to the Python documentation and look up .isalpha(), len() and .append() functions. Is there an equivalent function to .isalpha() to make sure only numbers are entered?
- Look up dictionaries (or dicts) in Python and how to use them with while loops.
When you’re through, try this course to learn how to use Django to make web applications with Python.