While Loops
So far we have used the for loop to iterate over objects. But there is another type of loop in Python that works differently. The while loop.
The while loop works like this: while a condition is true,
keep doing something. It does not iterate over a collection
like a for loop does. Instead it keeps running as long as its
condition evaluates to True and stops the moment it
becomes False.
This brings us to one of the most important warnings in programming. The infinite loop. You may remember way back in part 5 when we first introduced the pyBox and got a taste of what an infinite loop looks like. With while loops, accidentally creating one is very easy to do.
The Infinite Loop
Take a look at this example:
while 1 < 2:
print("I'm looooooping...")
Because 1 < 2 is always
True and never changes, this loop will run forever.
Your program will freeze, your browser tab may crash, and if you
are running this in VS Code your terminal will lock up until you
force stop it. Be careful.
The same thing happens here:
num = 1
while num < 100:
print(num)
Because num never changes inside the loop, the condition
num < 100 is always True and the loop
runs forever.
break
One way to escape an infinite loop is to use break.
When Python hits a break statement it immediately stops
the loop and moves on. Adding a break after the print
in the example above means the loop will only ever run once regardless
of the condition.
num = 1
while num < 100:
print(num)
break
But break is not the right tool if you want the loop to
run a specific number of times. For that we need to update the
condition on each iteration.
Loading quiz...
Updating the Condition
The correct way to control a while loop is to update the variable
that the condition depends on inside the loop. This way the condition
eventually becomes False and the loop stops naturally.
num = 1
while num < 100:
print(num)
num = num + 1
Now on each iteration num increases by 1. Eventually
num reaches 100, the condition num < 100
becomes False and the loop stops. This is the standard
pattern for a while loop and you will use it constantly. It can also
be written using the shorthand num += 1 which means
exactly the same thing.
Try each of the following in the pybox below and run them one at a time:
- Run the loop with
breakand observe it runs only once - Remove
breakand addnum += 1and observe it runs 99 times - Change
num += 1tonum += 2and observe the difference
while / else
Just like an if statement, a while loop can
have an else block. The else block runs once
when the while condition becomes False. It does
not run if the loop was exited using break.
This is the key distinction and also the main reason
while/else is only useful in specific situations. If you
need to know whether a loop completed naturally or was interrupted by
a break, else gives you a clean way to
handle that.
num = 1
while num < 5:
print(num)
num += 1
else:
print("loop finished naturally")
Outside of this specific use case, while/else is rarely
seen in real world Python code. Do not feel the need to use it just
because it exists.
while vs for - When to Use Which
Both loops repeat code but they are designed for different situations. Choosing the right one makes your code cleaner and easier to understand.
- Use a for loop when you know exactly what you are iterating over. A list, a string, a range, a dictionary. If you have a collection of items and you want to do something with each one, a for loop is always the right choice.
- Use a while loop when you do not know how many times the loop needs to run. If the loop depends on a condition that changes based on user input, an external event, or some value that is calculated during the loop, a while loop is the right choice.
A simple way to think about it:
- for - "do this for each item in this collection"
- while - "keep doing this until something changes"
In practice you will use for loops far more often than while loops. While loops are most commonly seen in situations like waiting for a user to enter valid input, running a game loop that continues until the player loses, or polling a system until a response is received.
for vs while Side by Side
The best way to understand the difference between a for
loop and a while loop is to see them solve the exact
same problem side by side.
Both loops below print every item in the same list. The
for loop does it in two lines. The
while loop does it in four. Python
handles all of the index tracking automatically in a for loop. With
a while loop you are responsible for managing the index yourself.
The for loop is cleaner, shorter, and easier to read.
For any situation where you are iterating over a known collection,
it will almost always be the better choice.
The while loop however gives you more control. Because
you manage the index and the condition yourself, you can do things
a for loop cannot. You can skip items, jump to a specific position,
change the step dynamically, or keep looping based on conditions that
have nothing to do with the collection itself. This is what makes
while loops more dynamic and better suited for
situations where the number of iterations is not known in advance.
while True
One of the most powerful and commonly used patterns with a while loop
is while True:. Because True is always
True, this creates a deliberate infinite loop that runs
forever until a break statement is reached.
This pattern is extremely useful when combined with
input(). Instead of asking the user for input once and
hoping they get it right, you can keep asking until they give you
what you need. This is how real applications handle user input
validation. We will practice this in the exercises below.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named while_loops.py in your part48 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Basic while Loop
-
Task: Create a variable
num = 1. - Goal: Write a while loop that prints every number from 1 to 50. Then modify the loop to print only even numbers between 1 and 50 using the step. Write a comment explaining how you prevented the loop from running infinitely.
Exercise 2: Countdown
-
Task: Create a variable
num = 10. -
Goal: Write a while loop that counts down from
10 to 1 and prints each number. When the loop finishes print
"Blast off!"using theelseblock. Write a comment explaining when the else block runs and when it would not run.
Exercise 3: while True with input()
-
Task: Write a
while True:loop that asks the user to enter the secret word usinginput(). -
Goal: If the user types
"python"print"Access granted!"and break out of the loop. If they type anything else print"Wrong password, try again."and keep asking. Write a comment explaining whywhile Trueis the right choice for this kind of problem.
Exercise 4: while vs for
-
Task: Create a list
cities = ['Bangkok', 'Tokyo', 'London', 'New York', 'Sydney']. -
Goal: Write two loops that print every city in
the list. The first using a
forloop and the second using awhileloop. Write a comment explaining which one is cleaner and why, and when you might choose the while loop version over the for loop version.
Exercise 5: Input Validation
-
Task: Write a
while True:loop that asks the user to enter a number between 1 and 10 usinginput(). -
Goal: Convert the input to an integer and check
if it falls within the valid range. If it does print
"Valid input!"and break. If it does not print"Please enter a number between 1 and 10."and keep asking. Write a comment explaining why this is a more robust solution than asking for input only once.
Don't Forget to commit and Push!