Nearby lessons
24 of 159Python - range() Function
📌 What You Will Learn
- Define the range() function and the sequence it generates
- Use the three forms range(stop), range(start, stop), and range(start, stop, step)
- Apply the rules for start, stop, and step values
- Create reverse sequences with a negative step
- Identify when a range is empty
What Is range()?
The range() function generates a sequence of numbers.
It is commonly used with for loops.
Forms
range(stop)range(start, stop)range(start, stop, step)
Rules
- Start value is included.
- Stop value is excluded.
- Default start is
0. - Default step is
1.
Examples
for i in range(5):
print(i)
for i in range(1, 6):
print(i)
for i in range(1, 11, 2):
print(i)Reverse and Empty Range
Use a negative step for reverse order.
for i in range(10, 0, -1):
print(i)If a valid sequence cannot be generated, the range is empty.
Common Uses
Use range() for counters, indexes, sums, and repeated sequences.
📝 Key Takeaways
- range() generates a sequence of numbers
- The start value is included and the stop value is excluded
- The default start is 0 and the default step is 1
- A negative step creates numbers in reverse order
- If a valid sequence cannot be generated, the range is empty
- range() is commonly used with for loops
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3