How Python repeats actions efficiently using iteration
Loops allow your program to repeat actions without writing the same code multiple times. Python provides two main loop types: for loops and while loops.
for loops iterate over sequences such as lists, strings, or ranges.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for i in range(5):
print(i)
# Output: 0 1 2 3 4
for char in "Python":
print(char)
while loops run as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
Use break to stop a loop early:
for i in range(10):
if i == 5:
break
print(i)
Use continue to skip to the next iteration:
for i in range(5):
if i == 2:
continue
print(i)
You can place loops inside other loops:
for x in range(3):
for y in range(2):
print(x, y)
The else block runs when the loop finishes normally (not interrupted by break):
for i in range(3):
print(i)
else:
print("Loop completed.")
while loop (infinite loop).range() incorrectly (off‑by‑one errors).Now that you understand loops, you’re ready to learn how to organize reusable code using functions in Lesson 8: Functions and Parameters.
← Back to Lesson Index