BeginnerLesson firstCategory 16 of 20

For Loops

Iterate over sequences and ranges. Read the lesson first, then move through the exercises in order.

5 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Print 1 to 10

Study Material

Read the full lesson

Visiting every item

While a while loop runs as long as a condition is true, a for loop is designed to iterate over a collection of items.

In Python, for loops are incredibly readable. They read almost like plain English: "for each item in this collection, do something."

Looping through a string

A string is just a collection of characters. You can loop through it easily.

python
word = "Python" for letter in word: print(f"Give me a {letter}!")

Python automatically pulls out the first character (P), assigns it to the variable letter, and runs the indented code. Then it loops back, grabs the next character (y), and repeats until the string is completely finished.

The range() function

Often, you don't have a collection to loop through. You just want to repeat something a specific number of times.

Python provides the range() function for exactly this purpose.

python
for i in range(5): print(f"Countdown: {i}") # Output: # Countdown: 0 # Countdown: 1 # Countdown: 2 # Countdown: 3 # Countdown: 4

Remember zero-based counting? range(5) generates 5 numbers, starting from 0 and stopping before 5.

Customizing range()

Just like string slicing, range() can take a start, stop, and step.

python
# range(start, stop, step) for number in range(2, 11, 2): print(number) # Output: # 2 # 4 # 6 # 8 # 10

Why for loops are safer than while loops

With a while loop, you have to manually update your counter variable, or you risk an infinite loop.

A for loop manages the iteration automatically. Once it reaches the end of the collection (or the end of the range), it safely stops. You never have to worry about an infinite loop when using a standard for loop over a finite collection.

What this lesson should give you

After this lesson, you should understand how to:

  • write a for loop to iterate over characters in a string
  • use range() to loop a specific number of times
  • customize range(start, stop, step) to generate specific sequences of numbers
  • recognize that for loops handle the repetition and stopping condition automatically

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.