design, write and debug programs that accomplish specific goals, including controlling or simulating physical systems; solve problems by decomposing them into smaller parts.

use logical reasoning to explain how some simple algorithms work and to detect and correct errors in algorithms and programs

6.3a

LO: To use a for loop

We are going to leave our guessing game for now and look at a couple of new techniques that we can then use to improve our game and make others. We have looked at and used while loops, now we are going to look at using for loops.

A for loop is a loop that will run for a set number of times - for example, do this five times. Looking at the flowchart above we can see that a for loop will run for each item in a sequence. If we want a loop to run five times then we would use a sequence e.g. 0, 1, 2, 3, 4 so that the loop would run for each object in the sequence. Before we look at using a for loop we need to look at a way of generating these sequences. To do this we will use range() function.


#the range function accepts parameters
range(start, stop, step)

#create a sequence 0,1,2,3,4
range(5)

#create a sequence 3,4,5
range(3,6)

#create a sequence 5,7,9,11,13,15,17,19
range(5,20,2)

			

If we try these out in IDLE then we can see that it will print out the start and end of the sequence or just how we have defined the range. To see/print out the whole sequence we will need to use a for loop:


for i in range(5):
    print(i)

0
1
2
3
4

			

Let's look in detail at what is going on here:

You can try these with the other range() examples and see what the output is.



One more thing. You may have been wondering why the for loop was described as looping through each item in a sequence rather than just a sequence of numbers? Well it turns out that a for loop will loop through (or iterate over) a list. The range() function creates a list of numbers as we have seen but a string turns out to be a list of characters, try this in IDLE:


string = "Hello World"

for i in string:
    print(i)

			

Code Examples

Resources