Lesson 15 of 4038%

(Progress persistence is disabled until Phase 9)

Python
Beginner

for Loops

Iterate over a sequence of items.

for Loops

What You’ll Learn

You’ll learn how to iterate over sequences (like lists or strings) using a for loop.

The for Loop

A for loop is used for iterating over a sequence. This is less like the for keyword in other programming languages, and works more like an iterator method.

Looping through a List

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

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

Expected Output:

I love apples
I love bananas
I love cherrys

In the example above, fruit is a temporary variable that holds the current item being processed in the list. You can name it whatever you want (e.g., for x in fruits:).

Looping through a String

Even strings are iterable objects, they contain a sequence of characters:

word = "Python"

for letter in word:
    print(letter)

Expected Output:

P
y
t
h
o
n

Why use for loops?

Use for loops when you have a collection of items and you want to do something to every item in that collection.

Lesson Progress

Take QuizBuild a Python Project