Flat_Eric Contemplating Data Type Conversions

While Loops

won’t stop, don’t stop

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 break and observe it runs only once
  • Remove break and add num += 1 and observe it runs 99 times
  • Change num += 1 to num += 2 and 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.

A simple way to think about it:

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:

Exercise 1: Basic while Loop

Exercise 2: Countdown

Exercise 3: while True with input()

Exercise 4: while vs for

Exercise 5: Input Validation

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course