First we are going to create a simple example in the python interactive environment to show how looping over a list works. The steps are:
for
>>> fruit = ['apples','oranges','bananas'] >>> for item in fruit: ... print(f'The best fruit now is {item}')
The output should look like
The best fruit now is apples The best fruit now is oranges The best fruit now is bananas
If you want to want to use a loop as a counter, you could create a list of numbers and assign it to a variable like this.
numbers = [0,1,2,3,4,5,6,7,8,9,10]
and then run
>>> numbers = [0,1,2,3,4,5,6,7,8,9,10] >>> for number in numbers: ... print(f'The next number is {number}')
Which would print all the numbers from 0 to 10, but what if you wanted to count to 1000. It would be tedious to write all the numbers out in this way.
Instead we use the range() function:
range()
>>> for number in range(10): ... print(f'The next number is {number}')
Your output should look like this:
The next number is 0 The next number is 1 The next number is 2 The next number is 3 The next number is 4 The next number is 5 The next number is 6 The next number is 7 The next number is 8 The next number is 9
You can see that computers start counting at 0 as the first number, If you want to start counting at 1, you can still use the range() method.
>>> for number in range(1,10): ... print(f'The next number is {number}')
Should return the following:
The next number is 1 The next number is 2 The next number is 3 The next number is 4 The next number is 5 The next number is 6 The next number is 7 The next number is 8 The next number is 9
If you want to increment the counter by more than the default value of 1, perhaps if you wanted only odd numbers or even numbers for example. To do this you add a third parameter to the range() function as shown below.
>>> for number in range(1,10,2): ... print(f'The next number is {number}')
This should return the following:
The next number is 1 The next number is 3 The next number is 5 The next number is 7 The next number is 9
For this to work, the range() method needs 3 parameters. So if you are starting at 0 you need to include it, otherwise it won’t work. For example range(0,10,2) works, but range(10,2) will not.
range(0,10,2)