In , 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 a
for
loop.
for
loops allow you to cycle through a sequence of items: a
range of numbers, a list of items, a string and more. As an example, a
for
loop can be used to simply iterate through a list 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.
Essentially, the code ran through the code block 3 times, and with each
time through the loop, the loop variable x
was set to the next
item in the list.
Because counting through a list of numbers is very common, Python provides
a built-in function to help us do specifically that: range()
.
Range returns a sequence of numbers, from 0 up to the just before the number
we give it.
Here's an example:
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.
This time, you'll notice that the list starts counting at 0 not 1, as
that's how range()
works. You may remember from the concept that list items are counted starting from 0 as well.
We can also use for
loops to iterate through the items in a
list. Here's the example from the 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