Iteration in programmingCondition-controlled loops - using WHILE

When designing programs, there may be some instructions that need repeating. This is known as iteration, and is implemented in programming using FOR and WHILE statements.

Part ofComputer ScienceProgramming

Condition-controlled loops - using WHILE

Sometimes an needs to steps a specific number of times. In programming, condition-controlled loops are implemented using WHILE . uses the statement while (note the lowercase syntax the Python uses).

Consider this simple algorithm for adding up a series of inputted numbers:

  1. set the total to 0
  2. set more numbers to ‘yes’
  3. while more numbers is ‘yes’, repeat these steps:
    • input a number
    • add the number to the total
    • ask ‘Any more numbers? Yes/No’
  4. say what the total is

This algorithm would keep iterating until the answer at the end of the loop is ‘No’, ie it will continue to iterate WHILE there are more numbers to add. A condition-controlled loop would be used because there is no way of knowing in advance how many more numbers will need to be entered before the algorithm stops.

The Python (3.x) code for this algorithm would look like this:

total = 0
answer = "yes"
while answer == "yes": number = int(input("Type in a number: ")) total = total + number answer = input("Any more numbers? yes/no ")
print("The total is: ")
print(total)

Steps that are part of the loop are . Indentation tells the computer which steps are to be iterated.

The program works like this:

  • the ‘while’ statement is used to specify where the iteration starts
  • the condition ‘answer = “yes”’ is used to control the iteration. It must be set to “yes” at the beginning so the code runs at least once
  • the program tests the condition by checking if the variable ‘answer’ equals “yes”
  • if the condition is true, the program iterates
  • if the condition is false, the program moves on to the next step

This program iterates as many times as is necessary and will keep iterating as long as (while) the condition is met.