Concepts / While Loops in Python

While Loops in Python

The central pattern is condition, loop block, condition again. The loop continues only while the condition is true.

  • Programming

A Loop That Keeps Checking

A while loop repeats a block of instructions as long as its condition remains true. In the guessing example from the source, the variable running is set to True before the loop begins. Python checks running, executes the while block when it is True, checks running again after that block finishes, and repeats the process if running is still True.

Key point

The central pattern is condition, loop block, condition again. The loop continues only while the condition is true.

Tracing the Guessing Round

Worked example

Following the source example

Trace what happens when the guesses are 50, 22, and 23.

  1. 1
    First guess: 50

    The guess is greater than the number. The program prints, No, it is a little lower than that. The loop can continue because the running condition has not been made False.

  2. 2
    Second guess: 22

    The guess is less than the number. The program prints, No, it is a little higher than that. The loop can continue.

  3. 3
    Third guess: 23

    The guess equals the number. The program prints, Congratulations, you guessed it. The source then makes running False, so the next condition check stops the loop.

  4. 4
    After the loop

    Because the while condition has become False, the optional else block runs and prints, The while loop is over. The next statement then prints, Done.

Result

The source output ends with Congratulations, you guessed it., The while loop is over., and Done.

Compare guessguess and numberCongratulationsrunning = FalseCheck runningcontinue or stopA little lowerguess > numberA little higherguess < numberguess == numberguess > numberguess < numberafter branchafter branchafter branch
After the guess is compared with the number, which branch runs, and what happens next?

The comparison selects one of three outcomes. An equal guess produces the congratulations message and changes running to False. A lower guess produces the higher hint. A higher guess produces the lower hint. After any of these branches, Python returns to the loop condition and checks running again.

The Repeated Check

running = Truebefore loopCheck runningTrueWhile blockread input and compareLoop endsrunning = FalseCheck runningagainstartTrueblock finishesTrueFalse
When does Python return to the while condition, and how many times can the loop body execute?

A while loop does not decide only once whether to run. The condition is checked before the loop block runs and again after the block has executed. If the condition is still true, the block runs again. If it is false, Python leaves the loop and proceeds to the optional else block, if one exists, before continuing to the next statement.

Stopping After a Correct Guess

running = Trueloop continuesCorrect guessguess == numberrunning = Falseloop condition failsLoop endselse block may runwhile block runsset statenext check is False
How does setting the loop-running condition to False cause the while loop to stop?

In the source example, finding the correct number does not stop the loop in the middle of an unexplained process. The correct branch changes running to False. Python finishes that pass through the loop block, then checks the condition again. This time the condition is false, so the loop stops.

Key point

To understand termination, track the variable used as the loop condition. Here, running begins as True and becomes False after the correct guess.

Comparing Higher and Lower Guesses

guess < number22 compared with 23A little higherprinted messageguess > number50 compared with 23A little lowerprinted messagecondition is trueremaining case
How does Python decide whether to print a little higher or a little lower based on the comparison?

The source uses an if, elif, and else structure inside the while block. First it checks whether guess equals number. If not, it checks whether guess is less than number. When that second comparison is true, the program says the answer is a little higher. If neither comparison is true, the guess is greater than the number, so the program says it is a little lower.

The Optional Else Block

A while loop may have an else block after it. The source states that this else block executes when the while loop condition becomes False. It can execute when the condition is false on the first check, and it executes unless the loop is left with a break statement.

In the real world

In the guessing example, the else block prints The while loop is over. That message appears after running becomes False and the loop condition is checked again. The following statement then prints Done.

Mistakes Beginners Make

  • Common mistake

    Forgetting that the condition is checked again after the loop block.

    What it looks like

    Assuming that changing running to False immediately skips the remaining reasoning about the current pass.

    Why it fails

    The source explains that the condition is checked again after the block executes. The next check is what finds running to be False and ends the loop.

    Do this instead

    Trace the order as condition check, loop block, condition check again, and then either another pass or loop termination.

  • Common mistake

    Reversing the higher and lower messages.

    What it looks like

    Printing a little lower when guess is less than number.

    Why it fails

    When guess is less than number, the source prints that the answer is a little higher. A greater guess produces the little lower message.

    Do this instead

    Compare the guess with number before choosing the message: less means higher; greater means lower.

  • Common mistake

    Expecting the loop to stop simply because a correct guess was printed.

    What it looks like

    Printing Congratulations, you guessed it. without changing the loop-running condition.

    Why it fails

    In the source example, the correct branch also makes running False. That state change causes the next condition check to stop the loop.

    Do this instead

    Ensure that the condition used by the while loop becomes False when the intended stopping event occurs.

  • Common mistake

    Assuming the while else block runs after every loop exit.

    What it looks like

    Expecting it to run even when break leaves the loop.

    Why it fails

    The source states that the else block executes unless the loop is exited with a break statement.

    Do this instead

    Distinguish normal termination through a false condition from termination caused by break.

Practice the State Trace

MEDIUM

Using the source's guessing pattern, explain what happens when the first guess is lower than the number, the second guess is higher than the number, and the third guess equals the number. State which message appears after each comparison, when running changes, and why the while loop's else block runs afterward.

Hints
  • For a guess lower than number, use the source's little higher message.
  • For a guess higher than number, use the source's little lower message.
  • The correct-guess branch changes running to False.
  • The while else block runs when the condition becomes False, unless break exits the loop.

What do you think happens?

In the source example, after the guess equals the number and running becomes False, does the while block execute another time?

  • Yes, because the correct branch already printed a message

  • No, because the next condition check is False

  • Yes, because the else block makes the loop run again

Reveal answer
Answer:

No, because the next condition check is False.

The source states that Python checks the condition again after the loop block. Once running is False, the loop stops and the optional else block is considered.

Key Takeaways

  1. 1
    A while loop checks its condition before each pass through the loop block.
  2. 2
    After the loop block finishes, Python checks the condition again.
  3. 3
    In the guessing example, lower and higher guesses produce different messages, while a correct guess changes running to False.
  4. 4
    The while loop's else block runs when the condition becomes False, including when it is false on the first check, unless break exits the loop.
  5. 5
    To trace a while loop, follow the condition, the current branch, the condition-changing state, and the next condition check.

At a glance

  • A while loop repeats its block while its condition is True.
  • Python checks the condition again after every completed pass.
  • The source guessing example uses comparisons to choose higher, lower, or congratulations messages.
  • Changing running to False after the correct guess causes the next condition check to stop the loop.
  • A while loop's else block runs after normal termination through a False condition, but not when break exits the loop.

Related concepts

More concepts starting with W