Python Range

🐍 Python range()

The range() function is used to generate a sequence of numbers, commonly used in for loops.


 1. Syntax of range()


  • start → Starting number (inclusive, default = 0)

  • stop → Ending number (exclusive)

  • step → Increment (default = 1, can be negative for reverse)


 2. Using range() with a Single Argument


✅ Output:

0
1
2
3
4
  • Starts from 0

  • Stops before 5


 3. Using range() with Start and Stop


✅ Output:

1
2
3
4
5
  • Starts from 1

  • Stops before 6


 4. Using range() with Step


✅ Output:

0
2
4
6
8
  • Step = 2 → increment by 2 each time


Reverse Range (Negative Step)


✅ Output:

5
4
3
2
1

 5. Converting Range to List, Tuple, Set


 


 6. Using Range in Loops


 


 7. Nested Loops with Range



 8. Practical Examples

Sum of first N numbers


 

Multiplication Table



 9. Tips

  1. range() does not generate a list directly — it’s a lazy sequence (efficient for large numbers).

  2. Always remember stop is exclusive.

  3. Negative step can be used for counting down.


🧠 Practice Exercises

  1. Print all odd numbers from 1 to 20.

  2. Print numbers in reverse from 10 to 1.

  3. Print squares of numbers from 1 to 10.

  4. Create a list of numbers divisible by 3 using range().

  5. Nested loop: Print a 5×5 grid of numbers.

You may also like...