It's common to use a for loop to iterate over a sequence of numbers by using the function range(), which generates lists of arithmetic progressions.
To use the range() function, feed it the following arguments:
• Required: An integer specifying the end of the range
REMEMBER The range() function generates a list of numbers up to but not including the end-of-range number. For example, if you want a list of all the single digits, you would use 10, not 9, as the end of the range:
• Optional: An integer specifying the start of the range. It goes before the integer that specifies the end of the range. If left out, it defaults to 0.
This example shows a range() function with a starting number of 2.
Optional: An integer to add to the current number
• Optional: An integer to add to the current number to generate the next number. (This is called a step.) If left out, it defaults to 1.
If you include the step, you must include the start-of-range number.
This example shows a range() function with a step of 3.
Tip You can use range() with negative numbers, too, as shown here:
Was this article helpful?
Post a comment