We've already 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 though 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 # 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.
This is time # 5 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 (1, 2, 3...). There is no reason the
range needed to run from 1 to 5; it could have just as easily run from
10 to 20.
Here is another example:
The output from this code would be:
The countdown has begun...
5
4
3
2
1
BLAST OFF!!!
-- PROGRAM FINISHED --
We can also use for loops to iterate through the items in a list. Here's the example list we saw earlier -- 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 --