While loops#

Normally Python reads one statement at a time, one at a time. But loops give us the ability to repeat a set of statements. In this lesson we will be learning about while loops.

Table of Contents

Introduction#

A while loop is a compound statement. Like an if statement while loops include a conditional expression and a suite of statements that will be repeated until the expression evaluates to falsy.

Each time that the suite of statements is repeated in a loop it is called an iteration. Likewise, the process of repeating a loop is called iterating.

Syntax#

The syntax for a while loop is:

while CONDITION:
    BODY

CONDITION

an expression evaluated in a boolean context that determines if the loop keeps going

BODY

statements to execute each iteration

Here’s a simple example that will keep asking the user for their name until they answer.

Listing 57 while loop example#
1name = ""
2
3while not name:
4  name = input("What is your name? ")
5
6print(f"Hello there {name}!")
7

Exercises#

Exercise 16 (Heads or Tails)

Write a while loop that asks the user "Heads or tails?" until they answer with either "heads" or "tails". Hint: Use the not in operator.

Exercise 17 (Random numbers less than 50)

Write a while loop that prints a random number between 1 and 100 as long as the number is less than 50.

Quitting a loop#

The break statement can be used to stop loop iteration.

This example intentionally creates an infinite loop then in each iteration asks the user if they would like to keep going and uses the break statement if they reply with "n".

Listing 60 stopping a loop with break#
1import random
2
3while True:
4    num = random.randint(1, 10)
5    print("The number is:", num)
6    reply = input("Keep going? ")
7    if reply == "n":
8        break

Exercise#

Exercise 18 (Random number not divisible by ten)

Write a while loop that prints a random number between 1 and 1000 as long as the number is less than 500. If the number is divisible by 10, quit the loop. Hint: Use the % operator.

Skipping part of an iteration#

You can skip the rest of the statements in a loop iteration by using the continue statement.

This example uses the continue statement to skip the rest of the iteration if the user does not enter a number.

Listing 61 using the continue statement#
1balance = 100
2while balance > 0:
3    reply = input("amount: ")
4    if not reply.isnumeric():
5        print("Numbers only.")
6        continue
7    balance = balance - int(reply)
8    print("Your balance is:", balance)

Exercise 19 (Dice)

  1. Assign chances to 0

  2. Assign rolls to an empty list

  3. Write a loop that repeats 10 times. In each iteration:

    1. Assign random number between 1 and 6 to the num variable

    2. Print "You rolled: num"

    3. Add 1 to chances

    4. Ask the user if they want to keep the roll

    5. If they reply with "n", use the continue statement to skip the rest of the iteration

    6. Append num to a list of rolls

    7. Print the rolls list

Loop patterns#

In this section we’re going to go over some of the ways that loops are commonly used.

Incrementing and decrementing#

Often in programming we want to repeat a suite of statements a specific number of times.

One way to do this is to keep track of which iteration the loop is currently executing by incrementing or decrementing a number.

Listing 62 incrementing the i variable#
1i = 0
2
3while i < 10:
4  print("Iteration:", i+1)
5  i = i + 1

Exercise#

Exercise 20 (Countdown)

Write a loop that counts down from 3 to 1. In each iteration print out the current number then use the time.sleep function to pause for one second.

Infinite loops#

When a program is written in such a way that the loop condition is always met the result is called an infinite loop. These are easy to cause by mistake.

The simplest infinite loop is while True with no break:

Listing 63 while True#
1import time
2
3while True:
4  print("Are we there yet?")
5  time.sleep(1)

A common mistake is to forget to increment your counter, as demonstrated below.

Listing 64 forgetting to increment i#
1import time
2
3i = 0
4
5while i < 10:
6  print("Iteration:", i)
7  time.sleep(1)

Infinite loops are not always a bad thing though. In the example below an infinite loop is used to always return the user to a main menu.

Listing 65 infinite loop used to keep a program running#
 1CHOICES = {
 2  "draw": "draw a card",
 3  "play": "play a card",
 4  "pass": "pass this turn",
 5}
 6
 7def menu():
 8  """Print user interface, and act according to user choice"""
 9  print("menu:", ", ".join(CHOICES))
10  selection = input("> ").lower().strip()
11  if selection not in CHOICES:
12    print(f'"{selection}" is not a valid selection, try again.')
13    return
14
15  text = CHOICES[selection]
16  print(f"{text}...")
17
18def main():
19  """."""
20  while True:
21    menu()
22    print()
23
24main()

Iterating over a list#

You can use a while loop to iterate over the items in a list. To do this we’ll increment an i variable just like we did above but we’ll use the len() function to determine the length of the list and therefore how many times the loop should repeat.

Then we can use the i variable to access each item in the list.

Listing 66 iterating over a list#
1i = 0
2colors = ["red", "green", "blue"]
3
4while i < len(colors):
5  color = colors[i]
6  print("Color", i, "is:", colors[i])
7  i += 1

Exercise 21 (Lunch menu)

Print a lunch menu. Make a list of lunch choices for a menu. Use a while loop to print out each item in the list with the number next to it.

You can also use this to iterate over list-like values. For example, a string can be used like a list of characters. So we can use the same pattern to iterate over all of the characters in a string.

Listing 68 iterating over the characters in a string#
1word = input("Enter a word: ")
2
3i = 0
4while i < len(word):
5    print("Letter", i, "is:", word[i])
6    i += 1

Exercise 22 (Vowels)

Print the vowels in a word. Ask the user for a word then iterate over each letter. If the letter is a vowel print the letter. (Hint: make a list of vowels the use the in operator)

Nested loops#

Just like you can have an if statement inside of another if statement, you can also have a while loop inside of another while loop.

This example prints out a score card for three rounds of three players each.

rounds, players = 3, 3
r = 0
while r < rounds:
    print("Round:", r+1, "\n")
    p = 0
    while p < players:
        print("Player", p+1, "score:", "______________")
        p += 1
    print()
    r += 1
Round: 1 

Player 1 score: ______________
Player 2 score: ______________
Player 3 score: ______________

Round: 2 

Player 1 score: ______________
Player 2 score: ______________
Player 3 score: ______________

Round: 3 

Player 1 score: ______________
Player 2 score: ______________
Player 3 score: ______________

A few things to pay attention to with nested loops:

  • The child p counter needs to be set to 0 inside the parent loop. If you forget this, the score line for each player will only be printed in the first round.

  • The child p counter must be incremented inside of the child loop.

  • In this case it doesn’t matter, but you generally want to increment the r counter at the end of the parent loop, just in case you need to use the current value of r inside of the child loop.

Here’s another example that prints out a grid of x, y coordinates.

rows, cols = 5, 5
r = 0
while r < rows:
    c = 0
    while c < cols:
        output = str(r) + "," + str(c) + "   "
        print(output, end="")
        c += 1
    print("\n")
    r += 1
0,0   0,1   0,2   0,3   0,4   

1,0   1,1   1,2   1,3   1,4   

2,0   2,1   2,2   2,3   2,4   

3,0   3,1   3,2   3,3   3,4   

4,0   4,1   4,2   4,3   4,4   

Exercises#

Exercise 23 (multiplication-table)

Print a multiplication table grid with 9 rows and 9 columns.

Exercises#

Exercise 24 (Name Cheer)

Print a cheer for your name. For each letter print "Gimme a letter!". Then end it with, "What does it spell? name!"

Exercise 25 (Check Password)

  1. Assign a secret variable to a string of your choice for the correct password.

  2. Assign a chances variable to 3

  3. Assign a password variable to None

  4. Assign a locked variable to True

  5. Write a while loop that continues as long as password is not equal to secret.

  6. In the loop:

    1. Ask the user for the password using the input() function, and assign the result to password.

    2. If password is equal to secret, set locked to False

    3. Quit the loop if there are no more chances

    4. subtract 1 from chances

  7. After the loop: if locked is False

    1. Print "Welcome!"

Exercise 26 (Jolly Good Fellow)

Print the lyrics to the jolly good fellow song. "For he's a jolly good fellow..." three times, then “Which nobody can deny!” once.

Exercise 27 (12 Days of Christmas)

Print the 12 Days of Christmas song.

  1. Create a nested list, where each item is a list containing two items: the ordinal word for the day (ie “second”) and the gift for that day.

  2. Iterate over each day to print the parent day lyric "On the ordinal day of Christmas my true love gave to me gift."

  3. Use a nested while loop to iterate over each of the days lower than parent day in descending order.

  4. For each child day, print the lyric "day gift,"

Show lyrics
On the first day of Christmas my true love gave to me
  a partridge in a pear tree.

On the second day of Christmas my true love gave to me
  2 turtle doves,
  and a partridge in a pear tree.

On the third day of Christmas my true love gave to me
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the forth day of Christmas my true love gave to me
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the fifth day of Christmas my true love gave to me
  5 golden rings,
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the sixth day of Christmas my true love gave to me
  6 geese a laying,
  5 golden rings,
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the seventh day of Christmas my true love gave to me
  7 swans a swimming,
  6 geese a laying,
  5 golden rings,
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the eighth day of Christmas my true love gave to me
  8 maids a milking,
  7 swans a swimming,
  6 geese a laying,
  5 golden rings,
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the ninth day of Christmas my true love gave to me
  9 ladies dancing,
  8 maids a milking,
  7 swans a swimming,
  6 geese a laying,
  5 golden rings,
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the tenth day of Christmas my true love gave to me
  10 lords a leaping,
  9 ladies dancing,
  8 maids a milking,
  7 swans a swimming,
  6 geese a laying,
  5 golden rings,
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the eleventh day of Christmas my true love gave to me
  11 pipers piping,
  10 lords a leaping,
  9 ladies dancing,
  8 maids a milking,
  7 swans a swimming,
  6 geese a laying,
  5 golden rings,
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

On the twelfth day of Christmas my true love gave to me
  12 drummers drumming,
  11 pipers piping,
  10 lords a leaping,
  9 ladies dancing,
  8 maids a milking,
  7 swans a swimming,
  6 geese a laying,
  5 golden rings,
  4 calling birds,
  3 french hens,
  2 turtle doves,
  and a partridge in a pear tree.

Exercise 28 (Hangman)

Write a hangman game.

  1. Choose a short word, give the player 6 chances to guess letters

  2. Each turn:

    1. Print their chances with x to show used chances, and _ to show remaining
      example: chances: xx____

    2. Print the word, but replace _ for unguessed letters
      example: 5 letters: _e___

    3. Ask the player to guess a letter

    4. Bonus: make sure the user enters exactly one character

  3. Tell the user at the end if they won or lost

Reference#

Glossary#

While Loops#

while loop#

A compound statement that repeats a suite of statements as long as a condition evaluates to truthy.

infinite loop#

When a program is written in such a way that the loop continues forever.

increment#
incrementing#

Adding to a number, usually 1.

decrement#
decrementing#

Subtracting from a number, usually 1.

See also#