FOR LOOPS

In WHILE LOOPS, we discussed how while loops can be used to cycle through code an indefinite (or even an infinite) number of times. But, what about when you only want to cycle through a piece of code a specific number of times? For that, we can use another type of loop called for loop.

for loops allow you to cycle through a range of numbers, a list of items or even through a string. As an example, a for loop can be used to simply iterate through a range of numbers, and execute a statement (or set of statements) on each iteration:



If you ran that code, the output would be:

This is time # 0 through the loop.
This is time # 1 through the loop.
This is time # 2 through the loop.
This is time # 3 through the loop.
This is time # 4 through the loop.

Essentially, the code ran through the code block 5 times, and with each time through the loop, the loop variable (x) was set to the current range value (0, 1, 2...). You'll notice that the list starts counting at 0 not 1, and this is a common convention in most all programming languages.

Here is another example:



The output from this code would be:


The countdown has begun...
5
4
3
2
1
BLAST OFF!!!
-- PROGRAM FINISHED --

Notice that for this loop, we using the range function in a different way. If the range function is passed 3 parameters, they should have the values start, stop, and step:

In other words, range(5, 0, -1) could be read as "starting at 5, count down (step -1) to 0 (but don't include the final 0)".

We can also use for loops to iterate through the items in a list. Here's the example from the LISTS concept -- a list of the first five months of the year:



We can use a for loop to iterate through each item in that list and do what we want with it. As a simple example, we can print each item and also the number of letters it has:



Here's the output from that code:


January 7
February 8
March 5
April 5
May 3
-- PROGRAM FINISHED --

home