- One of the things that makes a computer useful is the ability to repeat an operation many times over at high speeds. This is called iteration or looping
- The FOR loop allows us to carry out a set of instructions a specific number of times
- The code within the loop must be indented
- The range arguments set the number of loops to perform: range(start,finish)
- The counter variable i displays the number of times the loop has executed
- Remember that the computer always starts counting at 0!
#Basic for loop to cycle a number of times
for i in range(0,5):
print("hello")
#Loop that prints the counter
for i in range(0,5):
print(i)
Tasks
- Type in the code and make sure that it works
- Modify the program so it prints out a list of numbers: 1-20
- Modify the program so it takes in a word and number, and prints the word the number of times specified
- Save and label your code
Extension Task
The code below adds an extra parameter to the range() function that controls the step, i.e. how many it jumps by each time it counts. The example below counts up in twos from zero to one hundred.
#Basic for loop to cycle a number of times
for i in range(0,100,2):
print(i)
Can you work out how to get the loop to count down from 100?