CMPUT 174 - While Loops
CMPUT 174 - While Loops
While Loops
June 20 2022 1
Lecture Outline
❏ while Statements
❏ Infinite Loops
June 20 2022 2
What is a while Statement?
● while statements are another type of
compound repetition statement that can be
used to evaluate code repeatedly
June 20 2022 3
while Statements
● A code example of a while statement using the
user’s input
June 20 2022 4
for Statements vs. while Statements
June 20 2022 5
for Statements vs. while Statements
● In some cases, we know exactly how many
times a suite will be repeated. In such cases we
use a for loop
● For example, if want to make a 3x3 Tic Tac Toe
board then we know that we have to make
exactly 9 squares
● We’ll look at
some examples
of using a for
loop
June 20 2022 6
for Statements vs. while Statements
● In some situations we do not know exactly how
many times a suite should be repeated
● For example, while playing a game of checkers,
each player makes a move. The moves are
made until one player wins. We don't know how
many moves each player will make.
● We’ll look at
some examples
of indefinite
repetition
June 20 2022 7
Infinite Loops
● When using while statements, be careful of
infinite loops
● Infinite loops happen when the expression in
the header of the while statement never
evaluates to False
June 20 2022 8
Infinite Loops
● Example of an infinite loop!
June 20 2022 9
Infinite Loops
● The main idea to prevent an infinite loop is to
ensure there is some way to make a change
within the suite of the while statement
● The expression in the header of the while
statement must evaluate to False at some
point in time
June 20 2022 10
Infinite Loops
● Changing the code so that it’s no longer an infinite loop!
June 20 2022 11
Reminder
● Online Activities:
○ Assigned Readings:
■ Module 4
○ Complete Quiz 1
June 20 2022 12
Sookie’s Bistro
June 20 2022 13
Practice Problem 1!
Trout Cakes or Seafood Medley-while loop
'''Sookie wants to make trout cakes for her
Bistro.
June 20 2022 14
Practice Problem 1!
June 20 2022 16
Practice Problem 1!
Create a program that helps Sookie
keep track of how many trouts she has caught
without exceeding any limits.
June 20 2022 18
Practice Problem 2!
Each customer gets 3 attempts to guess the
number of jelly beans in the jar.
June 20 2022 19
Practice Problem 2!
If the customer is able to guess correctly in the second
attempt they get a 25% off coupon that they can redeem
at their next order.
June 20 2022 20
Practice Problem 2!
If the customer is able to guess correctly in the
third attempt they get a 10% off coupon that they can
redeem at their next order.