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
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:
We decare the loop by using the for keyword.
We use a variable i to represent the objects (items) in the sequence - in this example i would be an integer variable representing the integers: 0, 1, 2, 3 and 4 in the sequence.
We use the function range() and include the argument 5 to generate a sequence of five integers.
Like the other statements we have looked at so far we use a colon : to tell Python we are going to include commands/instructions for the loop to carry out. In this case, the instructions would be carried out five times.
We use the print() command (that is indented to show that it is part of the for statement) to print the variable i to the screen. Looking at the flowchart you can see that the for loop will work its way through the sequence so the i variable will reference all the integers in the sequence returned from the range(5) function.
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)