Practice: range() Function

« Read the chapter

Q1. Print 1 to 10

BeginnerCoding

Print the numbers 1 to 10, each on its own line.

Goal: Use range(start, stop).

Q2. Odd numbers

BeginnerCoding

Print the odd numbers from 1 to 9 on one line separated by spaces.

Goal: Use a step.

Q3. Countdown

IntermediateCoding

Print 10, 8, 6, 4, 2 on one line separated by spaces.

Goal: Use a negative step.

Q4. Table of 7

IntermediateCoding

Print the multiplication table of 7 from 1 to 5 as '7 x 1 = 7' and so on.

Goal: Make a table.

Q5. Sum of squares

IntermediateCoding

Print the sum of squares of the numbers 1 to 5.

Goal: Use range with an accumulator.

Q6. Indexes of a list

IntermediateCoding

For ['a', 'b', 'c'] print each index and item like '0 a' using range(len()).

Goal: Loop over indexes.

Q7. Reverse a list

AdvancedCoding

Print the items of [1, 2, 3, 4] from last to first using range and indexes.

Goal: Use range backwards.

Q8. List of range

BeginnerOutput

What does this print?

Code
print(list(range(4)))

Goal: Know the default start.

Q9. Start and stop

BeginnerOutput

What does this print?

Code
print(list(range(3, 8)))

Goal: Know that stop is excluded.

Q10. Step three

BeginnerOutput

What does this print?

Code
print(list(range(0, 10, 3)))

Goal: Predict a stepped range.

Q11. Empty range

IntermediateOutput

What does this print?

Code
print(list(range(5, 2)))

Goal: Know when a range is empty.

Q12. Length of range

IntermediateOutput

What does this print?

Code
print(len(range(2, 20, 5)))

Goal: Count range items.

Q13. Membership

IntermediateOutput

What does this print?

Code
r = range(0, 20, 4)
print(12 in r, 10 in r)

Goal: Use in with range.

Q14. Negative start

AdvancedOutput

What does this print?

Code
print(list(range(-2, 3)))

Goal: Use negative numbers.

Q15. Fix the missing last number

BeginnerDebugging

The code should print 1 to 5 but stops at 4. Fix it.

Code
for i in range(1, 5):
    print(i, end=' ')

Goal: Fix an off-by-one error.

Q16. Fix the float step

AdvancedDebugging

This code raises TypeError. Fix it to print 0.0, 0.5, 1.0, 1.5 each on a line.

Code
for x in range(0, 2, 0.5):
    print(x)

Goal: Handle decimal steps.

Q17. Explain exclusion

BeginnerConceptual

Why does range(1, 4) not include 4?

Goal: Understand the stop rule.

Q18. Total of even numbers

IntermediateApplication

Use range to find the sum of even numbers from 2 to 20 and print it.

Goal: Combine sum and range.