Condition-controlled loops - using WHILE
Sometimes an algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. needs to iterationIn computer programming, this is a single pass through a set of instructions. steps a specific number of times. In programming, condition-controlled loops are implemented using WHILE statementThe smallest element of a programming language which expresses an action to be carried out.. PythonA high-level programming language. uses the statement while (note the lowercase syntax the Python uses).
Consider this simple algorithm for adding up a series of inputted numbers:
- set the total to 0
- set more numbers to ‘yes’
- while more numbers is ‘yes’, repeat these steps:
- input a number
- add the number to the total
- ask ‘Any more numbers? Yes/No’
- 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 indentingAdding spaces or tabs in front of blocks of code, making it easier for programmers to see which parts of the code relate to each other.. 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.