Course 4.1Lesson 2 of 5
range() makes a row of numbers. range(n) starts at 0 and stops before n, range(a, b) starts at a and stops before b, and range(a, b, step) goes up in steps. A negative step counts down. The stop value is never included, so range(1, 6) is the way to get 1 to 5. range(a, b) makes b - a numbers. Use list() to see all the numbers at once, and use range() with a for loop to repeat lines a known number of times, or to count up or down.
Try the code and the simulations beside the lesson.
After this lesson you can
range() with one, two or three numbers,In the last lesson, for i in range(3) ran the loop three times. Now let us look at range().
| Form | What it makes |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(2, 8) | 2, 3, 4, 5, 6, 7 |
range(0, 10, 3) | 0, 3, 6, 9 |
range(5, 0, -1) | 5, 4, 3, 2, 1 |
One number: the stop. The row starts at 0. Two numbers: the start and the stop. Three numbers: the start, the stop and the step, which is how much to add each time.
This is the number one mistake. The stop value is where the row ends, but it is not part of the row.
The first loop stops at 4, not at 5. To get the numbers 1 to 5, write range(1, 6): one more than the last number you want.
The same rule is true for the slices of a text (Chapter 5). It looks odd at first. But it has a good reason. The row range(a, b) has exactly b - a numbers, so range(2, 10) has 8 numbers, and range(n) has n numbers. Counting the rounds is easy.
A negative step makes the numbers go down. The start must then be bigger than the stop, or the row is empty.
The picture shows at most 12 dots. The code under it shows every number.
Ask yourself three questions.
For the even numbers from 2 to 20: start at 2, the first number you do not want is 22, and the step is 2. So range(2, 22, 2). Read the row aloud to check: 2, 4, 6, ... 20.
range(1, 10) stops at 9.range(1, 10, -1) is empty.range(1, 10, 0) gives an error.range(0, 1, 0.1) is a TypeError, because range() makes whole numbers only.list() when you print a range. print(range(5)) shows range(0, 5), not the numbers.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
range() makes.range(n) starts at 0 and stops before n.range(a, b) starts at a and stops before b. It has b - a numbers.range(a, b, step) goes up by the step. A negative step counts down.n, the stop must be n + 1 (or n - 1 when going down).Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
range(3, 7) make?range(10) make?range(10, 0, -5) make?range() for 1, 2, 3, ..., 100.Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.