This guide explains Loop Over a Numeric Range with range() through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
range() provides a lazy sequence of integers, typically used to repeat an action a specified number of times. Its optional start and step parameters control the values.
When You Would Use This
Print even ticket numbers from 2 through 10.
Step-by-Step Example
for ticket_number in range(2, 11, 2):
print(ticket_number)
How the Example Works
The loop produces 2, 4, 6, 8 and 10. The stop value 11 is excluded, and step 2 advances by two.
Example Output
2
4
6
8
10
Try It Yourself
Create a descending range from 10 through 2 using step -2.
Common Beginner Mistakes
- Expecting the stop boundary to be included.
- Using a step of zero, which is invalid.
- Assuming range stores a whole list of all numbers in memory.
Key Takeaways
range()provides a lazy sequence of integers, typically used to repeat an action a specified number of times.- The loop produces 2, 4, 6, 8 and 10.
- Avoid this mistake: Expecting the stop boundary to be included.