A for loop is used to iterate over a sequence such as a list, tuple, string, dictionary, or range.
Unlike a while loop, a for loop is commonly used when the number of iterations is known.
Syntax
for item in sequence:
# code block
Loop Through a List
Example:
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)
Output:
Apple
Banana
Mango
Loop Through a String
Example:
for char in "Python":
print(char)
Output:
P
y
t
h
o
n
Using the range() Function
The range() function generates a sequence of numbers.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
range() with Start and Stop
Example:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
range() with Step
Example:
for i in range(0, 11, 2):
print(i)
Output:
0
2
4
6
8
10
Break Statement
The break statement stops the loop immediately.
Example:
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
if fruit == "Banana":
break
print(fruit)
Output:
Apple
Continue Statement
The continue statement skips the current iteration and continues with the next one.
Example:
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
if fruit == "Banana":
continue
print(fruit)
Output:
Apple
Mango
Else Statement
The else block executes when the loop finishes normally.
Example:
for i in range(3):
print(i)
else:
print("Loop Finished")
Output:
0
1
2
Loop Finished
Nested For Loops
A for loop can be placed inside another for loop.
Example:
colors = ["Red", "Blue"]
fruits = ["Apple", "Banana"]
for color in colors:
for fruit in fruits:
print(color, fruit)
Output:
Red Apple
Red Banana
Blue Apple
Blue Banana
Loop Through a Dictionary
Example:
person = {
"name": "John",
"age": 25
}
for key in person:
print(key, person[key])
Output:
name John
age 25
Using enumerate()
The enumerate() function adds a counter to an iterable.
Example:
fruits = ["Apple", "Banana", "Mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 Apple
1 Banana
2 Mango
Practical Example
Print the multiplication table of 5.
Example:
for i in range(1, 11):
print(f"5 x {i} = {5 * i}")
Output:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Summary
- A
forloop is used to iterate over a sequence. - It works with lists, tuples, strings, dictionaries, and ranges.
- The
range()function generates a sequence of numbers. - Use
breakto stop a loop. - Use
continueto skip an iteration. - Use
elseto execute code after the loop completes. - Nested loops allow looping inside another loop.