7.4. The Range Function¶
You can use the range
function to create a list of numbers. If the range
function is passed just one value it will return a list of all the numbers from 0 to one less than that number.
- range(5)
- This will return a list of all the numbers from 0 to 4.
- range(6)
- This will return a list of all the numbers from 0 to 5.
- range(7)
- This will return a list of all the numbers from 0 to 6.
Which of the following lines actually gives us a list of all the numbers from 0 to 5?
If two values are passed as input to the range
function then it will return a list of values that includes the first value, but ends at one less than the second value. It is inclusive of the first value and exclusive of the second value.
- range(10)
- That includes zero and doesn't include 10: [0,1,2,3,4,5,6,7,8,9]
- range(1,10)
- That doesn't include 10: [1,2,3,4,5,6,7,8,9]
- range(11)
- That includes zero: [0,1,2,3,4,5,6,7,8,9,10]
- range(1,11)
- That returns [1,2,3,4,5,6,7,8,9,10]
Which of the following lines actually gives us a list of all numbers from 1 to 10?
Let’s rewrite the program that calculates the product using the range
function to generate the list of numbers as shown below.
- 121645100408832000
- That is the product of all numbers from 1 to 19 (e.g., you changed the 11 to 20)
- 3628800
- That is the product of all numbers from 1 to 10 (e.g., no change at all)
- 362880
- That is the product of all numbers from 1 to 9 (e.g., you changed the 11 to 10)
- 2432902008176640000
- That is the product of all numbers from 1 to 20 (e.g., you changed the 11 to 21)
Change ONE number in the above program to tell us the product of all numbers from 1 to 20