Quarry School

Choose the bounds of range — quick review

In plain words

A row of seats is numbered from a first seat up to a sign that says where the row ends.

Rule

range(stop) gives the whole numbers from 0 up to but not including stop. range(start, stop) starts at start when start is below stop, and is empty otherwise. range(start, stop, step) moves by step each time and holds the numbers below stop for a positive step, or above stop for a negative one. stop is never included, and a step of 0 raises a ValueError.

Step

  1. Write the first number you want. That is start. It can be left out when it is 0 and no step is given, because a step needs a start before it.

  2. Choose the step. Leave it out to count up by 1, write a bigger number as the third number to skip, or a negative one to count down.

  3. Write the last number you want, and check that counting from start by the step lands on it; if it does not, change the start or the step. Then set stop past it, no more than one step beyond it: above it when counting up, below it when counting down. For a count up by 1, stop is the last number plus 1. In range(10, 0, -3) the last number is 1, and the stop 0 lies below it, within one step of 3.

  4. Check the count: for a step of 1 and a stop above start, range(start, stop) gives stop minus start numbers.

  5. Write out the numbers the range gives, or note that it gives none, and compare them with what you wanted.

Trap

The usual slip is a stop one short. range(1, 5) ends at 4, so a loop meant to count to 5 needs range(1, 6). Write out the last number of the range before you run the program.

Counting down needs a negative step. range(5, 1) holds no numbers, because its step is 1 and 5 is not below 1. The loop makes no passes and nothing is displayed. Write range(5, 1, -1) for 5, 4, 3 and 2.