Lesson 7: Loops (for, while)

How Python repeats actions efficiently using iteration

Why Loops Matter

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.

The for Loop

for loops iterate over sequences such as lists, strings, or ranges.

Looping Through a List

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Looping Through a Range of Numbers

for i in range(5):
    print(i)
# Output: 0 1 2 3 4

Looping Through a String

for char in "Python":
    print(char)

The while Loop

while loops run as long as a condition is true.

count = 0

while count < 5:
    print(count)
    count += 1

Breaking Out of Loops

Use break to stop a loop early:

for i in range(10):
    if i == 5:
        break
    print(i)

Skipping Iterations

Use continue to skip to the next iteration:

for i in range(5):
    if i == 2:
        continue
    print(i)

Nested Loops

You can place loops inside other loops:

for x in range(3):
    for y in range(2):
        print(x, y)

Looping with else

The else block runs when the loop finishes normally (not interrupted by break):

for i in range(3):
    print(i)
else:
    print("Loop completed.")

Common Loop Pitfalls

Next Steps

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