You are now able to write "for" loops, which will iterate over the letters in a string or through a range of numbers. The "for" loop will repeat a fixed number of times - once for each of the items in the string 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" Loop Syntax
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 True or 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>:
statement 1
statement 2
statement 3
print("After loop ends")
Copy
Three indented statements forming loop bodyAfter 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.

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.
However, if the user enters the wrong password, the logical expression is True, and the loop will continue to run 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.
Example: Countdown
You can use any kind of logical expression in a "while" loop. Study the code below. Can you predict the output before you run the program? Try it and see if you are right!

Try It Now


You can experiment with different logical expressions and updates to the blastoff variable on your own.

The Dreaded "Infinite Loop"
A "while" loop will continue to loop until the logical expression becomes False. 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.")
Copy
Look closely at the body of the loop. There are no statements inside the body that will update the password variable. So, if the password value is not equal to "SECRET" at the beginning, the logical expression will be True and 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 a "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.
Nested Loops
Nested Loops IllustrationYou have seen example "for" and "while" loops where the logic inside each loop body contains a series of sequential statements or perhaps some if() logic to make decisions. It is possible to write complex code inside a loop body - including placing a loop within a loop! This concept is called nesting or nested loops.

With nested loops, you have an outer loop and an inner loop. The inner loop will run to completion each time the outer loop iterates once! The examples below show how "for" and "while" loops might be nested in different combinations.

# nested for() loops
for <range 1>: # outer loop
# some outer loop logic
for <range 2>: # inner loop
# some inner loop logic

# nested while() loops
while <logical expression 1>: # outer loop
# some outer loop logic
while <logical expression 2>: # inner loop
# some inner loop logic

# outer for() loop and inner while() loop
for <range>: # outer loop
# some outer loop logic
while <logical expression>: # inner loop
# some inner loop logic

# outer while() loop and inner for() loop
while <logical expression>: # outer loop
# some outer loop logic
for <range>: # inner loop
# some inner loop logic
Copy
To demonstrate, here is a simple program with nested "for" loops. The outer loop will iterate over each letter in the word, and the inner loop will iterate over the numbers 1 through 4, printing each number on the same line.

Try It Now


When you run the program, you can see the inner loop runs multiple times - once for each outer loop iteration. Notice that the statements in the inner loop body are indented further to the right than the statements in the outer loop body!

Here is another example with an outer "while" loop and a "for" loop nested inside. Study the code closely; can you predict what will happen?

Try It Now

The outer loop will continue as long as the number is less than 10. The inner loop will iterate over the numbers 1 through 3. The output will be a sequence of numbers from 1 to 3, repeated 9 times.

1. How long will a "while" loop continue iterating?

Select one:

a.
An infinite number of times; there is no way to break out of a "while" loop

b.
As long as the loop's logical expression is True

c.
For the number of times specified in the range()

d.
As long as the loop index variable is equal to False

b. As long as the loop's logical expression is True

2. How many times will a "while" loop iterate if the logical expression is False when the first "while" statement is reached?

Select one:

a.
0

b.
Infinite loop

c.
1

d.
It depends on the logic inside the loop body

a. 0

3. How many times will the body of the following loop be run?

secret = input("Guess my secret: ")
while secret != "I am a superhero":
secret = input("Guess my secret: ")
print("Good guess")
Select one:

a.
1

b.
0

c.
It depends on the user's input

d.
Once for each character in "I am a superhero"

c. It depends on the user's input

4. What will be displayed when the following code is run?

mystery = 0
while mystery <= 4:
mystery = mystery + 1
print(str(mystery))
Select one:

a.
5

b.
4

c.
3

d.
6

a. 5

5. What is the problem with the following code?

sum = 0
while (sum >= 0):
sum = sum + 1
print("total = ",sum)
Select one:

a.
You can't update the sum variable inside a "while" loop

b.
This is an infinite loop

c.
The print statement is invalid

d.
The "while" statement should not have parentheses around the logical expression nor a colon (:) at the end