🔁 Loops and Iteration
Description: Loops allow you to repeat code without writing it many times. This is useful for handling lists, strings, or running logic multiple times.
Basic for loop
for i in range(5):
print(i)
0
1
2
3
4
1
2
3
4
Basic while loop
i = 0
while i < 5:
print(i)
i += 1
0
1
2
3
4
1
2
3
4
Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
banana
cherry
Loop through a string
word = "loop"
for char in word:
print(char)
l
o
o
p
o
o
p
Using break
for i in range(10):
if i == 5:
break
print(i)
0
1
2
3
4
1
2
3
4
Using continue
for i in range(5):
if i == 2:
continue
print(i)
0
1
3
4
1
3
4
Using pass
for i in range(3):
pass
print("Loop finished")
Loop finished
Using range(start, stop, step)
for i in range(1, 10, 2):
print(i)
1
3
5
7
9
3
5
7
9
Nested for loops
for i in range(2):
for j in range(2):
print(i, j)
0 0
0 1
1 0
1 1
0 1
1 0
1 1
While loop with countdown
count = 3
while count > 0:
print("Countdown:", count)
count -= 1
Countdown: 3
Countdown: 2
Countdown: 1
Countdown: 2
Countdown: 1
Sum using loop
total = 0
for i in range(1, 6):
total += i
print("Sum:", total)
Sum: 15
Find even numbers
for i in range(1, 6):
if i % 2 == 0:
print(i, "is even")
2 is even
4 is even
4 is even
✅ Summary
forloops are for sequences (like lists, strings, or ranges).whileloops run while a condition is true.breakexits the loop early.continueskips the current iteration.passdoes nothing (placeholder).