Introduction
Loops allow you to execute a block of code repeatedly.
For Loop
# Loop through a range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loop
count = 0
while count < 5:
print(count)
count += 1
Loop Control
# Break - exit loop
for i in range(10):
if i == 5:
break
print(i)
# Continue - skip iteration
for i in range(5):
if i == 2:
continue
print(i)
Practice Problems
- Print multiplication table (1-10)
- Find factorial using loop
- Count even and odd numbers in a list
- Search for element in list
- Pattern printing (triangles, pyramids)