Range Function
Range Function
When using loops, you will often want to repeat something a certain number of times.
For example:
- Print numbers from 1 to 5
- Repeat a message 3 times
- Count from 10 down to 1
Python gives us a helpful tool for this called range().
What Is Range?
range() creates a sequence of numbers.
It is commonly used with a for loop.
for number in range(5):
print(number)
What Happens Here?
Python creates numbers starting from 0.
So the output is:
0
1
2
3
4
It stops before 5.
Start and Stop
You can choose where to start.
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
The first number is the start.
The second number is where to stop (not included).
Step Value
You can also choose how much to move each time.
for number in range(2, 11, 2):
print(number)
Output:
2
4
6
8
10
This counts by 2.
Counting Backwards
Use a negative step.
for number in range(5, 0, -1):
print(number)
Output:
5
4
3
2
1
Code Along
for number in range(1, 4):
print("Hello", number)
Mini Challenge
Build a number printer.
Steps:
- Use
range() - Print numbers from
1to10
Real World Use Case
Programs use range() for counting items, repeating tasks, generating numbers, and creating timers.
Quiz
- What does
range()create? - Does
range(5)include5? - What does the third value in
range()do? - How do you count backwards?
Assignment
Create a program that prints even numbers from 2 to 20 using range().
Summary
You learned how range() creates numbers for loops, how start and stop work, and how to count forward or backward.