Python While Loops

Outside Resources:

W3schools – Python While Loops

InteractivePython – While Loops

Snakify Interactive Tutorial – While loop

Corey Schafer – Loops (starting at 6:14)

TheNewBoston – While loops (first half of video)


A while loop repeats a block of code until a condition is no longer true.

condition is a statement that is either True or False.

Examples:

x < 10
‘item’ in list_name
name == “Sue”

Example while loop using a stepper variable:

counter = 0
while counter < 4:
    counter += 1
    print("This loop has run this many times:")
    print(counter)

The condition in the loop above is “counter<  4” — the loop will continue to repeat as long as that condition is True. Eventually stepper will reach a value of 4, and “4 < 4” will be False, and the loop will stop repeating.

The counter variable in this example keeps track of the number of times a loop has run. The counter must be incremented (add one) inside the loop, or the loop will never be able to end. In other words, if we took out the “counter += 1” command, the “counter < 4” condition would be True forever, and the loop would never be able to finish.

A counter (also called a stepper sometimes) can be useful if you want to use it as the index of a list or string. Example:

words = ['cat', 'dog', 'sky', 'pizza']
counter = 0
while counter < len(words):
    print "Word "+str(counter)+ ": " + words[counter]
    counter += 1

This is different than the way we used for loops to iterate through a list. In this case, there is no walker variable, like “w” in “for w in words.”  Instead of using “w” or some other walker variable inside the loop, we see “words[counter]” as a way of getting the next word in the list, where “stepper” is the word number. This allows us to use both the number (index) and the word itself in the code. Notice that the print commands say “Word 0,” “Word 1,” and so on, which wouldn’t work in a “for w in words” type of loop.

Optional Bonus: find a for loop example on the internet that uses the “enumerate” Python function if you want to know a fast way to create a counter variable with a for loop.

Caution: if your while loop condition can’t become False, the loop will be infinite and your software might hang or crash.

Using a while loop with a counter variable is honestly a little silly… this is something that can be done more easily using a for loop.

When to use a while loop

If you don’t know how many times the code needs to repeat, that is a sign that you want a while loop. For example, if you need the user to keep entering responses until they give a valid response, that’s a use for a while loop. You don’t care how many times the code has to repeat – you just want your condition to be satisfied.

Example:

response = input('Enter yes or no: ')
while response not in ['yes', 'no']:
    response = input('Enter yes or no: ')
print 'Valid response received.'

In this example, if the user enters ‘yes’ the first time, the while loop will execute zero times. If the user enters ‘potato’ a hundred times before saying ‘yes’ or ‘no,’ the program will keep asking for a new response that many times.

Caution: if you forget to include a input() command inside the while loop’s code block (a tabbed command after the while line), your program will get stuck in an infinite loop.

Infinite Loops and Break

You can create an infinite (forever) loop like this:

while True:
    print('This repeats forever')

You can use the break keyword to finish a loop. Here is an example:

while True:
    a = input('Continue? (yes or no)')
    if a == 'no':
        break
print('The infinite loop has been broken.')

Example Output:

Continue? (yes or no) yep
Continue? (yes or no) yes
Continue? (yes or no) sure
Continue? (yes or no) ok
Continue? (yes or no) no
The infinite loop has been broken.

Bonus: the break keyword can also be used to end a for loop early.