The while Loop

Image result for while loop flowchart

While loops repeat as long as a Boolean condition is met. The program’s input loop accepts values until the user enters a special value or a sentinel that terminates the input.

Conditional iteration requires that a condition be tested within the loop to determine whether the loop should continue. Such a condition is called the loop’s continuation condition. If the continuation condition is false, the loop ends. If the continuation condition is true, the statements within the loop are executed again. The while loop is suitable for this type of control logic. Here is an example of the syntax for the very basics of a while loop.

If the while condition is never met or the sentinel value is never entered, an error is caused called an infinite loop. An infinite loop guarantees that a user will never progress through the program.

To avoid this, you can also use a while loop for a count-controlled loop. There is a trade-off to this though. Count-controlled while loops have more complex coding because it includes a Boolean expression and two extra statements that refer to the count of loop iterations.

Another way to avoid errors is a break statement. The loop’s structure can be simplified if we receive the first input inside the loop, and break out of the loop if a test shows that the continuation condition is false. This implies postponing the actual test until the middle of the loops. Python includes a break statement that will allow us to make this change in the program.

Here is an example.

Leave a comment