The range() function is a built-in Python tool used to generate a sequence of integers. It is most commonly used in for loops to repeat an action a specific number of times.
Think of it as having three settings: Start, Stop, and Step.
1. The Three Ways to Use It
range(stop)Starts at0and goes up to, but does not include, thestopnumber. Example:range(5)gives you0, 1, 2, 3, 4.range(start, stop)Starts at thestartnumber and goes up to (but excludes)stop. Example:range(2, 6)gives you2, 3, 4, 5.range(start, stop, step)Starts atstart, stops beforestop, and jumps by thestepamount each time. Example:range(0, 10, 2)gives you0, 2, 4, 6, 8.
2. A Real Example
In your current lab file for_example.py, you are using:
for i in range(0, 10, 2):
print(i)
How Python reads this:
- Start: Begin at 0.
- Logic: Add 2 every time (the step).
- End: Stop before you reach 10.
That is why the output is 0, 2, 4, 6, 8. It skips 10 because range always stops just before the stop value.
3. Key Tips to Remember
- The "Up To" Rule: The
stopvalue is never included in the result. - Default Start: If you only provide one number, Python assumes you want to start at
0. - Negative Steps: You can even go backwards!
range(5, 0, -1)would give you5, 4, 3, 2, 1.
You can try changing the numbers in your for_example.py script and running it again to see how the sequence changes!