Concepts / While Loops in Python

While Loops in Python

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

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.

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

Tracing the Guessing Round

Following the source example

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

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.

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.

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.

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.

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

guess == numberguess > numberguess < numberafter branchafter branchafter branchCompare guessguess and numberCongratulationsrunning = FalseCheck runningcontinue or stopA little lowerguess > numberA little higherguess < number
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

startTrueblock finishesTrueFalserunning = Truebefore loopCheck runningTrueWhile blockread input and compareLoop endsrunning = FalseCheck runningagain
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

while block runsset statenext check is Falserunning = Trueloop continuesCorrect guessguess == numberrunning = Falseloop condition failsLoop endselse block may run
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.

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

condition is trueremaining caseguess < number22 compared with 23A little higherprinted messageguess > number50 compared with 23A little lowerprinted message
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 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

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

    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.

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

  • Reversing the higher and lower messages.

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

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

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

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

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

  • Assuming the while else block runs after every loop exit.

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

    Fix: 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. A while loop checks its condition before each pass through the loop block.
  2. After the loop block finishes, Python checks the condition again.
  3. In the guessing example, lower and higher guesses produce different messages, while a correct guess changes running to False.
  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. To trace a while loop, follow the condition, the current branch, the condition-changing state, and the next condition check.

Key Takeaways

  • 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.