While Loops

While Loops

A while loop implements the repeated execution of code based on a statement that resolves to be either True or False. The code that is in a while block will execute as long as the while statement evaluates to True. When you enter into a while loop, it may not be obvious how long the loop will run, and in fact, the loops could run forever! A while loop whose statement will never resolve to False is called an infinite loop as it will continue to run forever.

The Structure

In Python, while loops are constructed as:

while [a condition is True]:
  [do something]

For example:

message = 'hello everyone'
counter = 0

while counter < len(message):
    counter = counter + 1

In this example, the while statement that needs to be True in order to run the block of code is that the value of the integer counter must be less than the length of the string message. Using a counter variable as part of the conditional statement is very common.

You'll notice that after the while statement, there is a colon (:) to denote the end of the statement. The line(s) of code to be run when the statement is True is indented under the while statement. You can use two spaces or a tab to indent your code. Python is very picky about spacing, so you must indent code when writing loop statements and you must do so consistently (no mixing spaces and tabs).

Other Examples of While Loops

In the first example of a while loop, the while statement was checking to see if counter was larger than len(message). Here's an example of what's called a Sentinel loop. This type of loop is looking for a variable to take on a specific value, and will continue to run the indented code until that value is reached. Typically, this type of loop is used when looking for a particular value or keypress to be inputted. For example, a correct password or a command to quit.

The example below is a loop that will repeatedly ask the user to input text until they enter the string unicorn.

password = ''

while password != 'unicorn':
    print('Enter the password: ')
    password = input()
print('Correct password entered!')
Enter the password: 
Enter the password: 
Enter the password: 
Enter the password: 
Correct password entered!

Notice that first the string password had to be created, even though it was empty, otherwise the while statement password != 'unicorn' would have created an error, since Python would not have a way to check if the string password had the value unicorn stored to it if it didn't exist. This process of initializing a string to the empty string, '', is a common technique to create a variable so it can be referenced before you store a value to it.

This while loop uses a string method .isalpha() to enforce a name requirement that insists the name have letters, no numbers, no symbols, and no spaces.

first_name = ''

while ( not first_name.isalpha() ):
    first_name = input()

This last example would be one way to print all the even numbers between 0 and 26.

counter = 0

while counter <= 26:
    print( counter )
    counter = counter + 2

As you can see, there are a lot of ways you can use a while loop. The flexibility does come at a price. It's very easy to unintentionally create a while loop that never terminates, either through improperly written code or an unexpected starting condition such that the while statement never returns False. The next type of loop, the for loop, is less flexible but has the benefit that it will always terminate.