Iteration is the process of repeating a process over and over. Often in programming you need to repeat a block of code several times.
FOR Loops
A for
loop is known as a count controlled loop, you should use it when you want to repeat a block of code for a set number of times.
How the for loop works
- a
for
loop will repeat for a set number of times and it will repeat between two ranges.range(min_value,max_value)
will repeat between the bottom and the top value but not include the top value. range(1,5)
will repeat 4 times, 1,2,3,4 but not 5 as it doesn’t repeat for the maximum value.x
is just a variable that is a counter and stores the number in the loop, this is useful if you need to use it in calculations.
Example Program 1 - Name Repeater Program
This program asks the user to enter their name and their age. It will then print
their name for the number of times their age.
When run in IDLE:
Example Program 2 - Times-table Program
This program will ask the user what timestable they want to learn, it will then calculate the timestables for that number. It makes use of the counter (x) in the loop to calculate the answer.
When run in IDLE:
Example Program 3 - Total Calculator Program
This program asks the user to enter a five digit number. It then uses sub-strings to add digits 1,3 and 5 together and subtract digits 2 and 4. This program combines using an if
with a for
loop.
When run in IDLE:
The answer on this example is 15. This is because it will add the first, third and fifth digit to the total (5 + 6 + 9) which gives 20. It then subtracts digits 2 and 4 (3 + 2) from the total, therefore 20 - 5 to give 15.
Example 4 - Finding the average of numbers in a list
This program has a list that contains test scores
. The program will go through the list and add together all the numbers to get a total. It then works out the average of the test scores.
When run in IDLE:
This program gives the average of 9 based on the values in the scores list. This is because 10 + 12 + 7 + 6 + 10 = 45. This is then divided by the size of the list (5) to give 9.