鶹Լ

Count-controlled loops - using FOR

Sometimes an needs to steps a specific number of times. In programming, count-controlled loops are implemented using FOR . uses the statements for and range (note the lowercase syntax that Python uses):

  • for determines the starting point of the iteration
  • range states how many times the program will iterate

Consider this simple algorithm for adding up five inputted numbers:

  1. set the total to 0
  2. repeat this section five times
    • input a number
    • add the number to the total
  3. go back to step 2
  4. say what the total is

This algorithm would allow five numbers to be inputted and would work out the total. A count-controlled loop would be used because it is known, in advance, how many times the algorithm needs to loop.

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

total = 0
for count in range(5):
	number = int(input("Type in a number: "))
 	total = total + number
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 program uses the variable ‘count’ to keep track of how many times the iteration has occurred.
  • The ‘for’ statement is used to specify where the loop starts.
  • The ‘range’ statement specifies how many times the loop is to happen.
  • The variable ‘count’ controls the iteration.
  • With each iteration, Python automatically adds 1 to the value of ‘count’.
  • The program keeps iterating as long as the value of ‘count’ is in the range specified in the loop (in this case as long as ‘count’ is in the range 0 to 5). Once it reaches the end of the range (5) the iteration stops.

This program iterates five times. To have a different number of iterations, the value ‘5’ would simply have to be changed to the number of times required.