Loops in Python
Loops are used to execute a block of code repeatedly. They help reduce repetition and make programs efficient.
💡 Python mainly uses for loops and while loops.
For Loop
A for loop is used to iterate over a sequence such as a list, string, or range.
for i in range(1, 6):
print(i)
While Loop
A while loop runs as long as a condition is true.
count = 1
while count <= 5:
print(count)
count += 1
Loop Control Statements
- break – exits the loop
- continue – skips the current iteration
- pass – does nothing (placeholder)
for i in range(1, 6):
if i == 3:
continue
if i == 5:
break
print(i)
Common Mistakes
❌ Infinite loops due to wrong condition
❌ Forgetting to update loop variables
❌ Forgetting to update loop variables
Practice Exercises
- Print numbers from 1 to 10 using a loop
- Print even numbers between 1 and 20