How does range() function work?

QuestionsQuestions4 SkillsProDec, 21 2025
0156

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 at 0 and goes up to, but does not include, the stop number. Example: range(5) gives you 0, 1, 2, 3, 4.

  • range(start, stop) Starts at the start number and goes up to (but excludes) stop. Example: range(2, 6) gives you 2, 3, 4, 5.

  • range(start, stop, step) Starts at start, stops before stop, and jumps by the step amount each time. Example: range(0, 10, 2) gives you 0, 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:

  1. Start: Begin at 0.
  2. Logic: Add 2 every time (the step).
  3. 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 stop value 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 you 5, 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!

0 Comments

no data
Be the first to share your comment!