Unit 05 · lesson

`while` Loops and Unknown Repetition

while Loops and Unknown Repetition

Core path: 30 minutes

What if the program cannot know in advance how many times the work will repeat?

A for loop is a natural fit when you already have a sequence or a known number of iterations.

A while loop is different. It keeps repeating while a condition remains true.

That means the loop's future depends on changing state.

Read the condition before the body

count = 1

while count <= 5:
    print(count)
    count += 1

Trace it:

count = 1
1 <= 5 ? True → print 1 → count becomes 2
2 <= 5 ? True → print 2 → count becomes 3
3 <= 5 ? True → print 3 → count becomes 4
4 <= 5 ? True → print 4 → count becomes 5
5 <= 5 ? True → print 5 → count becomes 6
6 <= 5 ? False → stop

The condition is checked before each iteration.

So a while loop is not simply "repeat this block." It is:

check state → maybe execute → update state → check again.

Run the bounded trace below and read the state transition after every body execution:

while_state.py
OutputRun with button or Ctrl/Cmd+Enter
Run the code to see output.
Ready to edit. Press Run when you want evidence.

Follow check, body, update, check. Change the update to count += 2 and explain how the state transition changes the number of iterations.

Change the update from count += 1 to count += 2. The important observation is not just that fewer lines print. Explain which future condition checks changed because the state transition changed.

Infinite loops are usually missing state transitions

Remove the update:

count = 1

while count <= 5:
    print(count)

What changes the value that controls the condition?

Nothing.

If count <= 5 was true before the first iteration, it stays true forever.

That is the mechanism behind this infinite loop.

Whenever you write while, ask:

What exact state change could make this condition false?

Then find the line that can produce that change.

If you cannot find it, the loop probably has no exit path.

Unknown repetition does not mean uncontrolled repetition

A password prompt may need one attempt or ten:

correct_password = "python1337"
password = ""

while password != correct_password:
    password = input("Password: ")

print("Access granted.")

We do not know the iteration count ahead of time.

We do know the stopping condition:

password == correct_password

That distinction matters.

Unknown count is fine. Undefined exit behavior is not.

Add more than one stop path deliberately

Suppose the requirement says the user gets at most three attempts.

correct_password = "python1337"
attempts = 0

while attempts < 3:
    password = input("Password: ")

    if password == correct_password:
        print("Access granted.")
        break

    attempts += 1
    print("Incorrect password.")

Now the loop can stop because:

password is correct → break
or
attempts reaches 3 → while condition becomes False

There are two exit paths, and both come from the requirement.

Watch where the counter changes

In the attempt loop, attempts += 1 occurs only after an incorrect password.

That design choice matters.

If you increment before checking the password, the count may represent a different idea: total attempts instead of failed attempts.

Neither is automatically wrong. The variable name and requirement should agree with what you are counting.

A command loop is a tiny application

command = ""

while command != "quit":
    command = input("Command: ").lower()

    if command == "status":
        print("System online.")
    elif command == "help":
        print("Commands: status, help, quit")
    elif command == "quit":
        print("Shutting down.")
    else:
        print("Unknown command.")

There are two layers of control here:

while → should the application keep accepting commands?
if/elif/else → what should this particular command do?

That is already recognizable as a command-line application loop.

for and while express different kinds of knowledge

Use a for loop naturally when the program knows what it is iterating over:

for player in players:
    ...

or has a known range:

for step in range(20):
    ...

Use while naturally when repetition depends on a changing condition:

while command != "quit":
    ...
while battery > 20:
    ...

Do not convert one into the other simply because you prefer the syntax.

The loop type should match what the program knows about repetition.

Trace a user-controlled loop

command = ""
count = 0

while command != "quit":
    command = input("> ").lower()
    count += 1
    print(f"Commands entered: {count}")

Suppose the user enters:

status
help
quit

Trace:

iterationcommand after inputcountcontinue?
1status1yes
2help2yes
3quit3condition false next check

Notice that the body still finishes the quit iteration before the condition is checked again, unless code explicitly breaks earlier.

That detail matters when output appears after the user enters a stop command.

Diagnose the loop instead of force-stopping it

When a loop seems stuck, ask:

  1. What condition controls repetition?
  2. What values appear in that condition?
  3. Which line changes those values?
  4. Does that line definitely execute?
  5. Is there an alternate path that skips the update?
  6. What exact state should make the loop stop?

Those questions will solve more problems than smashing Ctrl+C and rewriting everything.

Ctrl+C is still useful when you actually create an infinite loop. Use it to regain control, then investigate the state transition you forgot.

Choose the loop from the scenario

Explain your choice:

  1. print numbers 1 through 100;
  2. ask for a password until correct;
  3. process every character in a username;
  4. keep showing a menu until Exit;
  5. run a robot simulation for exactly 20 steps;
  6. continue monitoring until a stop signal becomes true.

The answer is not just for or while. State what controls termination.

Vocabulary lab

Flip the idea, not just the card

Explain the term before you reveal the back. Then compare your explanation with the definition, example, and warning.

1 / 4
Read all terms without animation
while Loop
A loop that repeatedly executes while its condition evaluates to True. Example: while command != 'quit': Do not confuse it with: A for loop that iterates over a sequence or range.
Stop Condition
The state or rule that determines when repetition should end. Example: command == 'quit' eventually makes command != 'quit' false. Do not confuse it with: A random break added because the loop design is unclear.
Infinite Loop
A loop that continues without reaching an intended stopping condition. Example: while count <= 5 when count never changes. Do not confuse it with: A loop with an unknown number of iterations but a valid exit path.
State Transition
A change in program state that can affect what happens next. Example: attempts changes from 2 to 3 and causes attempts < 3 to become false. Do not confuse it with: Repeating the same state forever.