Practice: range() Function
Q1. Print 1 to 10
Print the numbers 1 to 10, each on its own line.
Goal: Use range(start, stop).
Q2. Odd numbers
Print the odd numbers from 1 to 9 on one line separated by spaces.
Goal: Use a step.
Q3. Countdown
Print 10, 8, 6, 4, 2 on one line separated by spaces.
Goal: Use a negative step.
Q4. Table of 7
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
Print the sum of squares of the numbers 1 to 5.
Goal: Use range with an accumulator.
Q6. Indexes of a list
For ['a', 'b', 'c'] print each index and item like '0 a' using range(len()).
Goal: Loop over indexes.
Q7. Reverse a list
Print the items of [1, 2, 3, 4] from last to first using range and indexes.
Goal: Use range backwards.
Q8. List of range
What does this print?
print(list(range(4)))Goal: Know the default start.
Q9. Start and stop
What does this print?
print(list(range(3, 8)))Goal: Know that stop is excluded.
Q10. Step three
What does this print?
print(list(range(0, 10, 3)))Goal: Predict a stepped range.
Q11. Empty range
What does this print?
print(list(range(5, 2)))Goal: Know when a range is empty.
Q12. Length of range
What does this print?
print(len(range(2, 20, 5)))Goal: Count range items.
Q13. Membership
What does this print?
r = range(0, 20, 4)
print(12 in r, 10 in r)Goal: Use in with range.
Q14. Negative start
What does this print?
print(list(range(-2, 3)))Goal: Use negative numbers.
Q15. Fix the missing last number
The code should print 1 to 5 but stops at 4. Fix it.
for i in range(1, 5):
print(i, end=' ')Goal: Fix an off-by-one error.
Q16. Fix the float step
This code raises TypeError. Fix it to print 0.0, 0.5, 1.0, 1.5 each on a line.
for x in range(0, 2, 0.5):
print(x)Goal: Handle decimal steps.
Q17. Explain exclusion
Why does range(1, 4) not include 4?
Goal: Understand the stop rule.
Q18. Total of even numbers
Use range to find the sum of even numbers from 2 to 20 and print it.
Goal: Combine sum and range.