The Range Function

You can use the range function to loop over a sequence of numbers.

If the range function is called with a single positive integer, it will generate all the integer values from 0 to one less than the number it was passed and assign them one at a time to the loop variable.

    csp-7-4-1: Which of the following calls to the range function will generate the numbers from 0 to 5?
  • range(5)
  • This will return a the numbers from 0 to 4.
  • range(6)
  • This will return a the numbers from 0 to 5.
  • range(7)
  • This will return a the numbers from 0 to 6.

If two integer values are passed as input to the range function then it will generate each of values from the first value to one less than the second value. It is inclusive of the first value and exclusive of the second value.

    csp-7-4-2: Which of the following calls to range generates integers from 3 to 12?
  • range(12)
  • That starts at zero and doesn't include 12.
  • range(3, 12)
  • That doesn't include 12.
  • range(11)
  • That generates integers from 0 to 10.
  • range(3, 13)
  • That's what we want, integers from 3 to 12.

Let’s rewrite the program that calculates the product using the range function to generate the list of numbers as shown below.

    csp-7-4-3: Change one number in the above program to tell us the product of all integers from 1 to 20
  • 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)

Define a function to calculate the sum of 1 to the passed number using the range function. Return the sum from the function. Call the function and print the result.

Next Section - There’s a Pattern Here!