Why Do We Need Loops?
Loops let you repeat a block of code multiple times without writing it again and again. Python has two main types: the for loop and the while loop.
The for Loop
A for loop iterates over a sequence — a list, tuple, string, or range of numbers.
for i in range(5):
print(i)
# Output: 0 1 2 3 4
courses = ["Python", "Data Science", "AI"]
for course in courses:
print("Course:", course)
Understanding range()
range(5) # 0, 1, 2, 3, 4
range(2, 6) # 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8 (step of 2)
The while Loop
A while loop keeps running as long as its condition stays True.
count = 1
while count <= 5:
print(count)
count += 1
Careful: if the condition never becomes False, you'll create an infinite loop that never stops on its own.
Loop Control Statements
break — exits the loop immediately
for num in range(10):
if num == 5:
break
print(num)
# Output: 0 1 2 3 4
continue — skips the current iteration
for num in range(5):
if num == 2:
continue
print(num)
# Output: 0 1 3 4
else with loops
Python lets you attach an else block to a loop — it runs only if the loop finishes without hitting a break.
for num in range(3):
print(num)
else:
print("Loop finished without break")
Nested Loops
for i in range(3):
for j in range(2):
print(i, j)
for vs while — Which One to Use?
- Use for when you know how many times to loop, or you're iterating over a collection
- Use while when the loop should continue until some condition changes — the number of iterations isn't known upfront
Key Takeaways
forloops iterate over sequences;whileloops run based on a conditionbreakexits a loop early,continueskips to the next iteration- Always make sure a
whileloop's condition will eventually become False to avoid infinite loops