Hone

Lessons · Python · range()

Counting a fixed number of times

range gives you a run of numbers, starting where you say and stopping BEFORE the number you end with.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Do this five times. Number these rows. Try three times before giving up. Anything that repeats a known number of times is this, and the stop-before rule is why it lines up with positions counted from zero.

How to think about it

Ask: how many times, and do I need the number itself? If you never use the counter, that is a hint the loop could be simpler.

Worked example

for i in range(3):
Three turns, with i being 0, then 1, then 2.
    print(i)
Prints 0, 1, 2. Never 3: it stops BEFORE the number given.
for n in range(2, 5):
Two numbers means start and stop.
    print(n)
Prints 2, 3, 4. It begins AT the first and stops BEFORE the second.

Your turn

Print hello five times.

for i in range():
    print("hello")

The trap

Expecting range(3) to include 3. It does not, and that is deliberate: range(len(items)) then matches the valid positions exactly.

Practise range() on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.