range
: A Deeper LookFunction range
also has two- and three-argument versions. As you’ve seen, range
’s one-argument version produces a sequence of consecutive integers from 0
up to, but not including, the argument’s value. Function range
’s two-argument version produces a sequence of consecutive integers from its first argument’s value up to, but not including, the second argument’s value, as in:
In [1]: for number in range(5, 10):
...: print(number, end=' ')
...:
5 6 7 8 9
Function range
’s three-argument version produces a sequence of integers from its first argument’s value up to, but not including, the second argument’s value, incrementing by the third argument’s value, which is known as the step:
In [2]: for number in range(0, 10, 2):
...: print(number, end=' ')
...:
0 2 4 6 8
If the third argument is negative, the sequence progresses from the first argument’s value down to, but not including the second argument’s value, decrementing by the third argument’s value, as in:
In [3]: for number in range(10, 0, -2):
...: print(number, end=' ')
...:
10 8 6 4 2
(True/False) Function call range(1,
10)
generates the sequence 1 through 10.
Answer: False. Function call range(1,
10)
generates the sequence 1 through 9.
(IPython Session) What happens if you try to print the items in range(10,
0,
2)
?
Answer: Nothing displays because the step is not negative (this is not a fatal error):
In [1]: for number in range(10, 0, 2):
...: print(number, end=' ')
...:
In [2]:
(IPython Session) Use a for
statement, range
and print
to display on one line the sequence of values 99 88 77 66 55 44 33 22 11 0
, each separated by one space.
Answer:
In [3]: for number in range(99, -1, -11):
...: print(number, end=' ')
...:
99 88 77 66 55 44 33 22 11 0
(IPython Session) Use for
and range
to sum the even integers from 2
through 100
, then display the sum.
Answer:
In [4]: total = 0
In [5]: for number in range(2, 101, 2):
...: total += number
...:
In [6]: total
Out[6]: 2550