Concepts / Understanding while Loops

Understanding while Loops

if guess == number: print 'Congratulations, you guessed it.' # this causes the while loop to stop running = False elif guess < number: print 'No, it is a little higher than that.' else : print 'No, it is a little lower than that.' else : print 'The while loop is over.' # Do anything else you want to do here print 'Done'

  • Programming

What a while Loop Does

A while loop is a way to repeat a block of code as long as a condition remains true. Unlike an if statement, which checks a condition once and then moves on, a while loop keeps checking the condition and re-executing the same block of code over and over until the condition becomes false. This is useful when you do not know in advance how many times you need to repeat something—you just know you need to keep going until a certain goal is reached.

The core idea is that a while loop has a condition (like 'running is True' or 'guess does not equal the target number') and a body (the indented block of code beneath it). Each time through the loop, the program checks the condition. If it is true, the body executes. After the body finishes, the program jumps back to check the condition again. This cycle repeats until the condition becomes false, at which point the loop exits and execution continues with any code after the loop.

The Anatomy of a while Loop

A while loop has three essential parts: the while keyword, a condition, and an indented block of code. The condition is evaluated as a boolean—it must be either true or false. The indented block is the body of the loop, and it runs only when the condition is true.

An optional else block can follow a while loop. This else block executes when the while condition becomes false—but only if you exit the loop normally (by the condition becoming false). If you break out of the loop with a break statement, the else block does not run. If the condition is false from the very first check, the else block still executes.

How a while Loop Executes: Step by Step

To understand while loops deeply, it helps to trace through exactly what happens at each step. The program first checks the condition. If the condition is true, it executes the entire body of the loop (all the indented code). Once the body finishes, the program does not move to the next statement after the loop—instead, it jumps back to re-check the condition. This cycle continues until the condition becomes false.

truefalseStartCheck conditionExecute loop bodyLoop backExit loopExecute else block(if present)Continue to nextstatement
How does the program repeatedly check the condition, execute the body, and eventually exit the loop?

A Concrete Example: Guessing Game

Consider a number-guessing game where the computer picks a secret number and the player keeps guessing until they get it right. The program needs to loop—asking for a guess, checking if it is correct, and giving feedback—until the player guesses correctly. This is a perfect use case for a while loop, because you do not know in advance how many guesses the player will need.

Tracing a Guessing Game Loop

A program has a secret number (23) and a running variable set to True. The player enters guesses. Show what happens through three iterations: guess 50, then 22, then 23.

Iteration 1: Check condition: running is True, so the condition passes. The loop body executes.

Iteration 1: Get input and check guess: Player enters 50. The program checks: is 50 equal to 23? No. Is 50 less than 23? No. So it prints 'No, it is a little lower than that.' running stays True.

Iteration 1: Loop back: The body finishes. The program jumps back to check the condition again.

Iteration 2: Check condition: running is still True, so the loop body executes again.

Iteration 2: Get input and check guess: Player enters 22. Is 22 equal to 23? No. Is 22 less than 23? Yes. So it prints 'No, it is a little higher than that.' running stays True.

Iteration 2: Loop back: The body finishes. The program jumps back to check the condition.

Iteration 3: Check condition: running is still True, so the loop body executes once more.

Iteration 3: Get input and check guess: Player enters 23. Is 23 equal to 23? Yes. The program prints 'Congratulations, you guessed it.' and sets running to False.

Iteration 3: Loop back and check condition: The body finishes. The program checks the condition: running is now False. The loop exits.

After the loop: The optional else block executes (printing 'The while loop is over.'), then any remaining code runs (printing 'Done').

The loop ran exactly three times, once for each guess, and exited when the correct number was guessed and running was set to False.

Loop Variable State Across Iterations

A key insight is that variables inside the loop can change from one iteration to the next. In the guessing game, the guess variable holds a different value each time through the loop—first 50, then 22, then 23. The running variable also changes: it stays True for the first two iterations but becomes False on the third. These changing values are what eventually make the condition false and allow the loop to exit.

condition still truecondition still truecondition now falseBefore loop startsrunning = TrueIteration 1 startrunning = TruePlayer enters guessguess = 50Iteration 1 endrunning = True (no change)Iteration 2 startrunning = TruePlayer enters guessguess = 22Iteration 2 endrunning = True (no change)Iteration 3 startrunning = TruePlayer enters guessguess = 23Iteration 3 endrunning = FalseLoop exitsrunning = False
What happens to the guess and running variables each time through the loop, and how does that eventually satisfy the exit condition?

The else Block and Loop Exit

When a while loop exits normally (because the condition became false), any else block attached to the loop will execute. This is different from an if statement—an if statement's else block runs when the condition is false from the start, but a while loop's else block runs after the loop has finished repeating. The else block is useful for cleanup or for printing a message that should appear only after the loop has completed.

Important: if you exit the loop using a break statement (which you will learn about later), the else block does not execute. The else block only runs when the condition naturally becomes false.

loop exitsCode inside whileblockRuns repeatedly, once periterationAsk for guess, checkanswerRepeats 3 times in guessinggameelse block(optional)Runs once, when conditionbecomes falsePrint 'The while loopis over.'Runs once after all guessesCode after loopRuns once, after loop andelse blockPrint 'Done'Runs once at the very end
What is the difference between code inside the while block and code that runs after the loop ends?

Common Mistakes with while Loops

  • Forgetting to update the loop variable inside the loop body

    The loop has no way to exit. The condition will always be true, and the program will be stuck in an infinite loop.

    Fix: Make sure that inside the loop body, you change the variable that the condition depends on. For example, add count = count + 1 at the end of the loop body.

  • Confusing the condition with the body

    The condition should describe when you want to keep looping, not when you want to stop. If you want to loop while the guess is wrong, the condition should be while guess != number.

    Fix: Think about what should be true for the loop to continue. Write the condition that describes that state.

  • Forgetting the colon after the condition

    Python requires a colon after the condition to mark the start of the indented block.

    Fix: Always include a colon after the while condition, just like you do with if statements.

  • Not indenting the loop body

    Python uses indentation to determine which code belongs inside the loop. Without indentation, the code is not part of the loop.

    Fix: Indent all code that should run inside the loop by one level (typically 4 spaces or one tab).

Predicting Loop Behavior

What do you think happens?

A program sets running = True and enters a while running: loop. Inside the loop, it prints 'Hello' and then sets running = False. How many times will 'Hello' be printed?

  • Zero times
  • One time
  • Two times
  • Infinitely many times
Reveal answer

Answer: One time

The condition running is True, so the loop body executes once. Inside the body, 'Hello' is printed and running is set to False. After the body finishes, the program checks the condition again. Now running is False, so the condition is false and the loop exits. The body never runs again, so 'Hello' is printed exactly once.

Practice: Tracing a Loop

MEDIUM

Trace through the following scenario step by step. A program starts with count = 0 and enters a while count < 3: loop. Inside the loop, it prints the value of count and then adds 1 to count. Write down: (1) how many times the loop body executes, (2) what values are printed, and (3) what the value of count is after the loop exits.

Hints
  • Remember that the condition is checked at the start of each iteration.
  • The loop continues as long as count < 3. When count reaches 3, the condition becomes false.
  • The body runs, then the condition is checked again. This cycle repeats.

Key Takeaways

  1. A while loop repeatedly checks a condition and executes its body as long as the condition is true. Once the condition becomes false, the loop exits.
  2. The loop variable (the variable in the condition) must change inside the loop body, otherwise the loop will run forever.
  3. Each time through the loop, the condition is re-evaluated from scratch. The state of variables may have changed since the last iteration.
  4. An optional else block executes when the loop exits normally (because the condition became false), but not if you break out of the loop.
  5. Code after the loop (outside the while block) runs only once, after the loop has finished and any else block has completed.

Key Takeaways

  • A while loop checks a condition and repeats its body as long as that condition is true.
  • The loop exits when the condition becomes false, and any else block then executes.
  • Loop variables must change inside the body to eventually make the condition false; otherwise the loop runs forever.
  • Code inside the loop body runs multiple times (once per iteration), while code after the loop runs only once.
  • Tracing through a loop step by step—checking the condition, executing the body, and updating variables—is the best way to understand what will happen.