Chapter 6, Lesson 4 Text URL

Chapter Six: Lists and Loops

Lesson Four: "While" Loops

 

You are now able to write "for" loops, which will iterate over a list items or through a range of numbers. The "for" loop will repeat a fixed number of times - once for each of the items in the list or range. However, in many situations, you may not know in advance how many times a loop will need to repeat. Instead, you just need a loop that will continue to repeat while a certain condition is true. For example, you may want to repeatedly ask the user for input until the correct input is given. You can use a "while" loop to handle these situations.

"while" Loops to Iterate while a Condition is True

A "while" loop is based on a logical expression that evaluates to either True or False. As long as this expression is True, the loop will continue to execute.  As soon as the expression becomes False, the "while" loop will end.

To create a "while" loop, start with the "while" keyword. Then, add a logical expression that evaluates to Trueor False. The expression might be very simple (e.g. just a Boolean variable) or very complex with multiple relational and logical operators. Add a colon at the end of the statement.

while <logical expression>:
   # execute these statements

After the "while" statement, indent the next line(s) of code that you want to belong to the "while" loop. These lines will form the "body" of the loop, just like indented lines underneath a "for" statement form the body of that loop.

Three indented statements forming loop body

Unlike a "for" loop, the "while" loop does not have an index variable.  The logical expression may contain any valid test such as (userInput != "q")  or (studentNumber < 5).  The while loop will continue executing so long as the logical expression is True. If the expression evaluates to False at the very beginning, the "while" loop body will never run at all - it will be skipped instead!

In the example below, we ask the user for a secret password. We then enter a "while" loop that checks to see if the password is a match for "SECRET". If it is a match, the loop is complete, and the program skips down to the next non-indented line. However, if the password is wrong, we print a message to the user and then prompt them for a new password.

Try It Now

How many times will the body of this "while" loop run? It depends on the user input! The logical expression is evaluated at the top of the loop before the loop body is run. If the user enters "SECRET" as the first answer, the logical expression will be False at the beginning, and the loop will never run.

Please enter your password: SECRET
Password verified.

But if the user enters the wrong password, the logical expression is True, and the loop will continue to run again and again until the right password is received.

Please enter your password: cookies
No, try again!
Please enter your password: secret
No, try again!
Please enter your password: SECRET
Password verified.

The Dreaded "Infinite Loop"

A "while" loop will continue to loop until the logical expression becomes False. In order for that expression to change from True to False, one or more of the variables or conditions within the expression must be changed by your logic inside the loop body. If your loop body does not ever cause the logical expression to become False, then you have created an infinite loop and your program will never leave that loop body!

Consider a similar version of our password-check program. Can you spot the problem?

password = input("Please enter your password: ")
while password != "SECRET":                       # loop until we get the right password
   print("No, try again!")                        # tell the user they goofed

print("Password verified.")

Look closely at the body of the loop. There are no statements inside the body that will update the passwordvariable. So, if the password value is not equal to "SECRET" at the beginning, the logical expression will be Trueand remain True forever. The "while" loop will just print "No, try again!" over and over again, and your program will be stuck in that loop forever.

It is very important that "while" loop's logical expression has some way to become False as the loop runs. Otherwise, your program will be stuck in an "infinite loop" forever. Carefully check your loop logic and make sure that the loop will end when you expect it to end.

"break", "continue" and "else" Statements

You can use "break", "continue" and "else" statements with a "while" loop. They work the same as they do in a "for" loop.

KeywordDescription
breakThis statement will immediately halt the loop, and the program will continue after the loop body.
continueThis statement will immediately halt the current loop iteration, and the program will continue at the top of the loop with a new evaluation of the logical expression.
elseThis statement after the loop body will mark a block of logic that will run after the loop completes normally. It is skipped if the loop exits due to a break statement.
 

In the following example, we challenge the user to guess a magic number. The "while" loop will continue until the user gets the right answer. However, if the user guesses a number greater than or equal to 1000, we decide they're just being silly and halt the game immediately with a break statement. A final "else" block at the end will congratulate the user for guessing correctly, as long as the loop exits normally.

Try It Now

Run the code to play the game yourself! Verify that it works as expected when you guess too high, too low, just right, or over 1000.

 

Creating a "while" Loop that will Run at Least Once

In some cases, you know you'll want to do something at least one time. Getting user input is a great example. If you want to verify user input - perhaps check a password - you need to get at least one input value and check it against the logical expression. If the expression is True and you enter the loop, you then need to re-prompt the user for a new value.

password = input("Please enter your password: ")

while password != "SECRET":                            # loop until we get the right password
   print("No, try again!")                             # tell the user they goofed
   password = input("Please enter your password: ")    # get a new password

print("Password verified.")

It's somewhat annoying to write the same statement twice - password = input("Please enter your password: ". How can we re-write this loop to avoid duplicate code?

Many languages have a built-in "do-while" loop that will always execute at least one time. A classic "do-while" loop will check the logical expression at the bottom of the loop instead of the top.

do:
   password = input("Please enter your password: ")    # get a new password
   if (password != SECRET):
      print("No, try again!")                          # tell the user they goofed

while password != "SECRET":

print("Password verified.")

However, the "do-while" loop does not exist in Python. Don't try to write the code pictured above, because it won't work!

Instead, we can use a "while" loop with an interesting logical expression and a break statement to get the same effect. Study the code below. Can you tell how it will always execute at least once, prompt the user for a password, verify the password, take the correct action, and exit the loop when successful?

Try It Now

Normally, a logical expression that is simply "True" means the loop would be infinite. However, since our loop body detects an ending condition and uses "break" to exit the loop, it's not as dangerous as it first looks. Run the code and verify for yourself that it works just like our original example at the beginning of the lesson.

 

Work with Me: What's in Your Pocket, Revisited

 

In the last lesson, you used a "for" loop to prompt the user to enter multiple items that he or she might find in a pocket. Let's write a similar program, but use a "while" loop instead. We won't worry about having a maximum number of items or a "full" pocket, just let the user enter as many items as desired.

Remember, when the user is prompted for a value with input(), simply hitting "Enter" without entering any data will result in an empty string ("") being returned from the input() function. This is the user's signal that no more items are present.

Your program should take the following general steps.

  1. Initialize an empty list called items (this is done for you below).
  • Use input() to prompt the user with "What's in your pocket? " and save the result in the itemvariable.
  • If the item variable is not empty, add the item to the items list.
  • If the item variable is empty, halt the loop immediately
  1. Finally, print the items list to the screen (this is done for you below).

We are leaving most of the detailed logic between steps 1 and 5 up to you! Be sure to use a "while" loop to manage these middle steps. You can create a traditional pattern with a meaningful logical expression at the top. Or, you can build a "do-while" pattern with a True logical expression and a break statement somewhere to exit the loop.

Try It Now

  

 

When you run the program, the user should be able to enter any number of items and hit "Enter" when done to see the entire list.

What's in your pocket? candy
What's in your pocket? coins
What's in your pocket? lint
What's in your pocket? mint
What's in your pocket?
Your pockets contain: ['candy', 'coins', 'lint', 'mint']

End of Lesson


Last modified: Wednesday, 8 May 2019, 9:00 AM