๐Ÿ

Python for Beginners

9/20 lessons

Course progress45%
Complete to earn 2,800 XP

Python for Beginners

For Loops & Iteration

Python for Beginners ยท Lesson 7+140 XP

For Loops & Iteration

In this lesson, you'll learn how to use for loops to iterate over sequences like lists, strings, and ranges. Loops are one of the most powerful tools in programming โ€” they let you repeat actions without copying code.

1

What is a for loop?

A for loop repeats a block of code for each item in a sequence. Think of it like reading a list out loud โ€” you say each item one by one until you reach the end.

example.py
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I like {fruit}")

Output:

I like apple
I like banana
I like cherry
2

Using range() with for loops

The range() function generates a sequence of numbers. This is perfect when you want to repeat something a specific number of times.

range_example.py
# Print numbers 0 through 4
for i in range(5):
    print(f"Count: {i}")

# Count from 1 to 10 (step by 2)
for num in range(1, 11, 2):
    print(num)

๐Ÿ’ก Key syntax

range(start, stop, step) โ€” start is inclusive, stop is exclusive. So range(1, 6) gives you 1, 2, 3, 4, 5.

3

Nested loops

You can put a loop inside another loop. The inner loop runs completely for every single iteration of the outer loop. This is called a nested loop.

nested.py
for row in range(1, 4):
    for col in range(1, 4):
        print(f"{row} x {col} = {row * col}")

Try it yourself

try_it.py
Ready to move on? Mark this lesson as complete to earn your XP.

Up next

While Loops