Introduction π
The range() function is used to generate a sequence of numbers. It is most commonly used inside for loops, but can also be converted into lists, iterated manually, or used in logic conditions.
Note
1. Basic Syntax π§±
range(stop)range(start, stop)range(start, stop, step)
2. range(stop) β Starts From 0 π’
range_stop.py
for i in range(5):
print(i)βοΈ Outputs: 0, 1, 2, 3, 4
βοΈ Stops before 5
3. range(start, stop) β Custom Start π
range_start_stop.py
for i in range(2, 6):
print(i)βοΈ Outputs: 2, 3, 4, 5
βοΈ Stop value is *exclusive*
4. range(start, stop, step) β With Step Size πΆββοΈ
range_step.py
for i in range(1, 10, 2):
print(i)βοΈ Outputs odd numbers: 1, 3, 5, 7, 9
5. Negative Step β Counting Backwards β¬οΈ
range_negative_step.py
for i in range(10, 0, -1):
print(i)βοΈ Countdown from 10 to 1
βοΈ Stop value (0) is excluded
6. Converting Range to List π
range_to_list.py
nums = list(range(1, 6))
print(nums) # [1, 2, 3, 4, 5]Note
7. Using Range in While Loop π
range_in_while.py
i = 0
nums = range(5)
while i < len(nums):
print(nums[i])
i += 18. Range With Conditions π§
range_condition.py
for i in range(1, 20):
if i % 5 == 0:
print(i)βοΈ Prints multiples of 5 between 1 and 19.
9. Using Range in Nested Loops πͺ
nested_range.py
for i in range(1, 4):
for j in range(1, 4):
print(i, j)10. Skipping Values With Step πββοΈ
skip_values.py
for i in range(0, 20, 3):
print(i)βοΈ Outputs: 0, 3, 6, 9, 12, 15, 18
11. Using Range for Indexing π
indexing_with_range.py
fruits = ["apple", "banana", "mango"]
for i in range(len(fruits)):
print(i, fruits[i])12. range() in Reverse Using reversed() π
range_reversed.py
for i in reversed(range(1, 6)):
print(i)13. Check If Value Exists in Range π
range_membership.py
print(5 in range(1, 10)) # True
print(10 in range(1, 10)) # False14. Range Efficiency π
range() is extremely efficient because it generates values on demand rather than storing them in memory.
Note
15. Real-World Example π
real_world_example.py
for attempt in range(1, 4):
pin = input("Enter PIN: ")
if pin == "1234":
print("Access granted")
break
print("Wrong PIN, attempt", attempt)Conclusion π
You now fully understand the range() function in Python! Want the next topic? Try Pass Statement, Functions, Parameters, or List Comprehensions. Just tell me! π