Python range()
Function
The range()
function is commonly used with for
loops when you want
to repeat something a certain number of times or iterate over a sequence of integers.
Basic form — range(n)
Produces integers from 0
up to n - 1
. If n
is zero or negative, the loop body will not execute.
for i in range(5): # 0, 1, 2, 3, 4
print(i)
Two parameters — range(a, b)
Produces integers from a
up to b - 1
. The start is inclusive, the stop is exclusive.
for i in range(2, 7): # 2, 3, 4, 5, 6
print(i)
Summing numbers from 1 to n
Use range(1, n+1)
to include n
in the sequence:
n = 5
total = 0
for i in range(1, n + 1):
total += i
print(total) # 15
Three parameters — range(a, b, step)
The third argument sets the step (positive or negative). For example:
- Odd numbers from 1 to 99:
range(1, 100, 2)
- Countdown from 100 to 1:
range(100, 0, -1)
# Odd numbers
for i in range(1, 100, 2):
print(i)
# Countdown
for i in range(100, 0, -1):
print(i)
Formal definition
In general, for i in range(a, b, step)
produces values:
i = a, a + step, a + 2*step, …
while i < b
if step > 0
,
or i > b
if step < 0
.
Practical uses
- Repeat an action a fixed number of times
- Iterate over indices of a list
- Create arithmetic progressions
- Work with backwards loops using negative steps
Key takeaway: range()
gives you flexible integer sequences for looping — from simple counters to custom step sizes and reverse iteration.