while loop - sentinel value

Objective

After working through this lesson, you’ll be able to

  • Write Python code using a while loop with a sentinel value.

Introductory Problem

Using a while loop, ask the user for the minutes of their bus/car ride 3 times. Print the sum of these numbers

intro.py
x = 3
sum = 0
while x > 0:
    ride = int(input("How long? "))
    sum = sum + ride
print("Sum:",sum)

while loop (sentinel)

Previously, you learned how to write loops that read and process a sequence of values. Today you will learn about while loops with sentinel values. A sentinel value denotes the end of a data set, but it is not part of the data. A loop that uses a sentinel value is called a sentinel-controlled loop.

1 <variable = input>

Ask the user for a value

2 while <condition>:

while loop executes while condition is True

3 <do something>

do something inside the while loop

4 <variable = input>

Ask the user for a value again

5 <do something>

(optional) do something outside the while loop

Use a variable named data to store the input value.

Examples

Example 1

Using a while loop, ask the user how long their bus ride was this month until they enter 0. Print the sum of these numbers.

Steps:

  • Initialize a variable sum to 0.

  • Ask "How long? (enter 0 to end): “

  • Create a condition that will execute until the user enters 0.

  • Sum the inputs

  • Print the sum after the user enters 0.

The input value 0 is the sentinel value for these loops.

Example 2

Using a while loop, ask the user for the length of their bus/car ride until the user enters 0. Print the average of these numbers.

Initialize a counter variable to 0. Every time a number is entered, increment the variable.

Example 3

Using a while loop, ask the user for the length of their bus/car ride until the user enters 0. Print the maximum of these numbers. Initialize max to the value of the first input.

Example 4

Using a while loop, ask the user to enter numbers until they enter 0. Print the total number of even numbers.

Conclusion

  • What is an example of when you would use a while loop that does not have a fixed number of inputs?

  • Explain the role of the sentinel variable.

Last updated

Was this helpful?