The for loop in Python is used to repeat a block of code multiple times. When used with the range() function, it is especially useful for numeric iteration.
This approach is commonly used when:
for variable in range(start, stop, step):
# code block
range()The range() function generates a sequence of numbers.
range():range(stop)range(start, stop)range(start, stop, step)for i in range(5):
print(i)
Output
0
1
2
3
4
Explanation
for i in range(1, 6):
print(i)
Output
1
2
3
4
5
for i in range(1, 10, 2):
print(i)
Output
1
3
5
7
9
Explanation
for i in range(5, 0, -1):
print(i)
Output
5
4
3
2
1
Explanation
num = 5
for i in range(1, 11):
print(num * i)
total = 0
for i in range(1, 6):
total += i
print("Sum =", total)
Output
Sum = 15
for Loop with range()for i in range(1, 4):
for j in range(1, 4):
print(i, j)
range() does not include the stop valuefor loop with range() is used for numeric iteration
range() generates a sequence of numbers
Forms:
range(stop)range(start, stop)range(start, stop, step)Supports: