Python Range

🐍 Python range() β€” Full Tutorial

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


πŸ”Ή 1. Syntax of range()

range(stop)
range(start, stop)
range(start, stop, step)
  • 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

for i in range(5):
print(i)

βœ… Output:

0
1
2
3
4
  • Starts from 0

  • Stops before 5


πŸ”Ή 3. Using range() with Start and Stop

for i in range(1, 6):
print(i)

βœ… Output:

1
2
3
4
5
  • Starts from 1

  • Stops before 6


πŸ”Ή 4. Using range() with Step

for i in range(0, 10, 2):
print(i)

βœ… Output:

0
2
4
6
8
  • Step = 2 β†’ increment by 2 each time


Reverse Range (Negative Step)

for i in range(5, 0, -1):
print(i)

βœ… Output:

5
4
3
2
1

πŸ”Ή 5. Converting Range to List, Tuple, Set

numbers = list(range(5))
print(numbers) # [0, 1, 2, 3, 4]
numbers_tuple = tuple(range(1, 6))
print(numbers_tuple) # (1, 2, 3, 4, 5)

numbers_set = set(range(3))
print(numbers_set) # {0, 1, 2}


πŸ”Ή 6. Using Range in Loops

# Print even numbers from 2 to 10
for i in range(2, 11, 2):
print(i)
# Print squares of numbers 1 to 5
for i in range(1, 6):
print(i**2)


πŸ”Ή 7. Nested Loops with Range

for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")

πŸ”Ή 8. Practical Examples

Sum of first N numbers

n = 5
total = 0
for i in range(1, n+1):
total += i

print(“Total:”, total) # 15

Multiplication Table

num = 5
for i in range(1, 11):
print(f"{num} x {i} = {num*i}")

πŸ”Ή 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.

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *