While loops
Contents
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
|
an expression evaluated in a boolean context that determines if the loop keeps going |
|
statements to execute each iteration |
Here’s a simple example that will keep asking the user for their name until they answer.
1name = ""
2
3while not name:
4 name = input("What is your name? ")
5
6print(f"Hello there {name}!")
7
Exercises#
(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.
Solution to Exercise 16 (Heads or Tails)
1answer = None
2while answer not in ["heads", "tails"]:
3 answer = input("Heads or tails? ")
(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
.
Solution to Exercise 17 (Random numbers less than 50)
1import random
2
3num = 0
4while num < 50:
5 num = random.randint(1, 100)
6 print(num)
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"
.
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#
(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.
Solution to Exercise 18 (Random number not divisible by ten)
1import random
2num = -1
3while num < 500:
4 num = random.randint(1, 1000)
5 print(num)
6 if num % 10 == 0:
7 print("num is divisible by 10, quitting")
8 break
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.
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)
(Dice)
Assign
chances
to0
Assign
rolls
to an emptylist
Write a loop that repeats
10
times. In each iteration:Assign random number between
1
and6
to thenum
variablePrint
"You rolled: num"
Add
1
tochances
Ask the user if they want to keep the roll
If they reply with
"n"
, use thecontinue
statement to skip the rest of the iterationAppend
num
to a list ofrolls
Print the
rolls
list
Solution to Exercise 19 (Dice)
1chances, rolls = 0, []
2
3while chances < 10:
4 num = random.randint(1, 6)
5 print(f"You rolled: {num}")
6
7 chances += 1
8
9 keep = input("Keep? ")
10 if keep.lower() == "n":
11 continue
12
13 rolls.append(num)
14 print(f"Your rolls so far: {rolls}")
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.
1i = 0
2
3while i < 10:
4 print("Iteration:", i+1)
5 i = i + 1
Exercise#
(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.
Solution to Exercise 20 (Countdown)
1import time
2
3num = 3
4while num >= 1:
5 print(f"{num}...")
6 num = num - 1
7 time.sleep(1)
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
:
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.
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.
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.
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
Solution to Exercise 21 (Lunch menu)
1choices = [
2 "Pepperoni pizza",
3 "Ham sandwich",
4 "Fish tacos",
5 "Bean burrito",
6]
7
8i = 0
9
10print("Lunch menu")
11print("----------", "\n")
12
13while i < len(choices):
14 item = choices[i]
15 print(f"{i+1}. {item}")
16 i += 1
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.
1word = input("Enter a word: ")
2
3i = 0
4while i < len(word):
5 print("Letter", i, "is:", word[i])
6 i += 1
(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)
Solution to Exercise 22 (Vowels)
1VOWELS = ["a", "e", "i", "o", "u", "y"]
2word = input("Enter a word: ")
3
4i = 0
5while i < len(word):
6 letter = word[i]
7 if letter in VOWELS:
8 print(letter, end="")
9 i += 1
10print()
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 to0
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 ofr
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#
(multiplication-table)
Print a multiplication table grid with 9
rows and 9
columns.
Solution to Exercise 23 (multiplication-table)
1SIZE = 9
2
3print()
4
5x = 1
6while x <= SIZE:
7 print(" ", end="")
8 y = 1
9 while y <= SIZE:
10 val = x * y
11 print(str(val).rjust(4), end=" ")
12 y += 1
13 x+=1
14 print("\n")
15
16main()
Exercises#
(Name Cheer)
Print a cheer for your name. For each letter print "Gimme a letter!"
.
Then end it with, "What does it spell? name!"
Solution to Exercise 24 (Name Cheer)
1import time
2
3NAME = "Alissa"
4
5i = 0
6while i < len(NAME):
7 print("Gimme a", NAME[i].upper() + "!")
8 i += 1
9 time.sleep(0.5)
10
11print("\nWhat does it spell?")
12print(NAME.upper() + "!")
(Check Password)
Assign a
secret
variable to a string of your choice for the correct password.Assign a
chances
variable to3
Assign a
password
variable toNone
Assign a
locked
variable toTrue
Write a while loop that continues as long as
password
is not equal tosecret
.In the loop:
Ask the user for the password using the
input()
function, and assign the result topassword
.If
password
is equal tosecret
, setlocked
toFalse
Quit the loop if there are no more chances
subtract
1
fromchances
After the loop: if
locked
isFalse
Print
"Welcome!"
Solution to Exercise 25 (Check Password)
1secret = "00000"
2password, locked, chances = None, True, 3
3
4while password != secret:
5 password = input("Enter the password: ")
6 if password == secret:
7 locked = False
8
9 if not chances:
10 print("Too many attempts, try again later.")
11 break
12
13 chances = chances - 1
14
15if not locked:
16 print("Welcome.")
(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.
Solution to Exercise 26 (Jolly Good Fellow)
1i = 0
2while i < 3:
3 print("For he's a jolly good fellow...")
4 i += 1
5
6print("Which nobody can deny!")
(12 Days of Christmas)
Print the 12 Days of Christmas song.
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.
Iterate over each day to print the parent day lyric
"On the ordinal day of Christmas my true love gave to me gift."
Use a nested
while
loop to iterate over each of the days lower than parent day in descending order.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.
Solution to Exercise 27 (12 Days of Christmas)
1import time
2
3DAYS = [
4 ['first', "a partridge in a pear tree"],
5 ['second', "turtle doves"],
6 ['third', "french hens"],
7 ['forth', "calling birds"],
8 ['fifth', "golden rings"],
9 ['sixth', "geese a laying"],
10 ['seventh', "swans a swimming"],
11 ['eighth', "maids a milking"],
12 ['ninth', "ladies dancing"],
13 ['tenth', "lords a leaping"],
14 ['eleventh', "pipers piping"],
15 ['twelfth', "drummers drumming"],
16]
17
18i = 0
19while i < len(DAYS):
20 day, gift = DAYS[i]
21 print("On the", day, "day of Christmas my true love gave to me")
22
23 x = i
24 while x >= 0:
25 gift = DAYS[x][1]
26 time.sleep(0.5)
27
28 # indent the line
29 line = " "
30
31 # add the "and" in "and a partridge in a pear tree"
32 if i and x == 0:
33 line += "and "
34
35 # add the number of gifts
36 if x:
37 line += str(x+1) + " "
38
39 # add the gift given
40 line += gift
41
42 # add the "," or "."
43 if x:
44 line += ","
45 else:
46 line += "."
47
48 # print the line
49 print(line)
50
51 x -= 1
52
53 i += 1
54
55 print()
(Hangman)
Write a hangman game.
Choose a short word, give the player 6 chances to guess letters
Each turn:
Print their chances with
x
to show used chances, and_
to show remaining
example:chances: xx____
Print the word, but replace
_
for unguessed letters
example:5 letters: _e___
Ask the player to guess a letter
Bonus: make sure the user enters exactly one character
Tell the user at the end if they won or lost
Solution to Exercise 28 (Hangman)
1import random
2
3WORDS = [ "hello", "goodbye", "secret", "satisfy", "apple", "bear" ]
4
5def info(turn, chances, guess):
6 """print the used vs unused chances and guessed vs unguessed letters
7 example:
8 chances: xx____ 7 letters: _e_____
9 """
10 print(" "*40, "chances:", ("x"*turn)+("_"*(chances-turn)), len(guess), "letters:", guess)
11
12def main():
13 """."""
14 turn, chances, word = 1, 6, random.choice(WORDS)
15 guess = "_" * len(word)
16
17 info(0, chances, guess)
18
19 while guess != word and turn <= chances:
20 char = input("Guess a letter: ").lower()
21 if not char:
22 continue
23 elif len(char) > 1:
24 print(" Just one letter!")
25 continue
26 if char in word:
27 letters = list(guess)
28 for i,c in enumerate(word):
29 if c == char:
30 letters[i] = c
31 guess = "".join(letters)
32 print(" "*40, "chances:", ("x"*turn)+("_"*(chances-turn)), len(word), "letters:", guess)
33 turn += 1
34 if guess == word:
35 print("You win!!")
36 else:
37 print("Too bad. The word was:", word)
38
39main()
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
.