While loops
Estimated Time: 1 hour
Often, we want code to keep going. For example, a password prompt might ask a user for their password until they enter a valid value. The program doesn’t know ahead of time how many tries the user will need. Instead, it knows when to stop asking — when the user enters a valid password. This type of situation is perfect for a while
loop.
In this section, we'll learn about while
loops. while
loops repeat a block of code until a condition is met.
while
loops
The syntax looks like this:
while condition:
block of code to execute
It’s a lot like an if
statement. It checks the condition, then runs the block of code if the condition is True
.
Unlike an if
statement, however, after executing the block, a while
loop checks the condition again and again. It only stops when the condition becomes False
.
Here’s a flow chart depicting a while
loop:
The flow of a while
statement is:
-
Evaluate the condition, the result will be True or False.
-
If the condition is False, exit the
while
statement and continue execution at the next statement (after the while loop block). -
If the condition is True, execute the body of the while statement and go back to Step 1
Examples
Here's an example asking the user for password:
# Set up the password
password = "super secret"
user_entry = ""
# While loop
while user_entry != password:
user_entry = input("What's the password?")
In the example above, the program will keep prompting the user for a password while the user's input is not the expected value.
Below is another example:
n = 5
while n > 0:
print(n)
n = n - 1
print('Blastoff!')
You can read the code in English as:
- The initial value of
n
is 5 - While
n
is greater than 0, display the value ofn
, and then reduce the value ofn
by 1 - When
n
is no longer greater than 0, display the string Blastoff!
The code will output:
5
4
3
2
1
Blastoff!
The condition we are checking before every loop is: "Is n
greater than zero?" This is a boolean expression that will yield either True
for 5, 4, 3, 2, and 1, or False
when the value of n
is 0.
What does a loop look like?
a = 1
while a < 10:
print(a)
a += 2
Let’s visualize how this code runs:
In the animation, you can see the variable a
change over time, and the loop condition checked before each execution of the loop body.
Loop Vocabulary
A while
loop has a condition and a body. The condition is what gets checked each time. The body is the code that runs again and again. Just like an if
statement, the body code has to be indented.
Every execution of the body of a while
loop is called an iteration. In the blastoff example, the body of the loop was executed five times, so the loop has five iterations.
Whether or not the loop body will be executed depends on whether or not the condition evaluates to True
or False
.
In the ‘blastoff’ example above, the loop is controlled by an iteration variable n
which tells the loop whether or not to proceed. The body of the loop changes the value of n
each time the loop runs, so that the loop eventually finishes running.
If n
did not change, the loop would repeat forever, creating an infinite loop.
Infinite loop
An infinite loop is a loop that runs forever. For example:
x = 4
while x > 0:
print("Run on!")
print ("Done!")
4 is always greater than 0, and x
never changes, so the loop runs forever.
If you accidentally write an infinite loop, you will have to figure out how to stop it. Sometimes you’ll need to force-close the program. If you accidentally run an infinite loop in Replit, press “Stop” at the top of the page, or press Control + C in the console.
Infinite Loop Demo
Practice: Loop Prediction
🤔 Look at the following code snippet. What will the output be? Why?
Think about it, write down what you think the result will be, then expand the solution.
i = 10
while i > 13:
print ('This is a while loop')
i = i + 1
Unfold to see the solution
The body of the loop will never get executed!
The condition i > 13
will be False
because 10 is not greater than 13. So, the body of the while loop will be skipped.