Often we want to do something a large number of times, in which case
typing all the numbers becomes tedious. The range() function
returns a list of numbers, allowing us to avoid typing them ourselves.
You should give range() at least two3.7 parameters3.8: first the number at
which the list
starts and then the number up to which the list should go.
Note that the second number itself is not in the range but
numbers up to this number are. This may seem strange but
there are reasons.
By way of example, we could have replicated the function of the
for loop above (3.6.1) using range(6) since:
>>> print range(0, 6)
[0, 1, 2, 3, 4, 5]
So we could have constructed the for loop as follows:
for i in range(0, 6):
print "i now equal to:", i
sumsquares = sumsquares + i**2
# etc.
Here is another example of the use of range():
>>> print range(5, 10)
[5, 6, 7, 8, 9]
If you are uncertain what parametes to give range() to get it to
execute your for loop the required number of times, just find the
difference between the first and second parameters. This is then the
number of times the contents of the for loop will be executed.
You may also specify the step, i.e. the difference between successive items. As we have seen above, if you do not specify the step the default is one.
>>> print range(10, 20, 2)
[10, 12, 14, 16, 18]
Note that this goes up to 18, not 19, as the step is 2.
You can always get the number of elements the list produced by
range() will contain (and therefore the number of times the
for loop will be executed) by finding the difference between
the first and second parameters and dividing that by the step. For
example range(10, 20, 2) produces a list with 5 elements since
.
The range function will only produce lists of integers. If you
want to do something like print out the numbers from 0 to 1, separated
by 0.1 some ingenuity is required:
for i in range(0, 10):
print i / 10
EXERCISE 3.6
Use the range function to create a list containing the numbers 4, 8, 12,
16, and 20.
Write a program to read a number from the keyboard and then print a
``table'' (don't worry about lining things up yet) of the value of
and
from 1 up to the number the user typed, in steps of,
say, 2.
range()
can actually be used with just one parameter (the number to stop at),
but you will make less mistakes if you use two.