🎓 A1Learner
🔍

Python For Loops

A for loop is a loop that visits each item in a sequence once. The loop variable takes each item in turn.

Walk over a string

A string is a sequence of characters.

for letter in "cat":
    print(letter)

Walk over a list

The variable color takes each list item in turn.

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

A first look at range

The range gives a short sequence of numbers. You study it fully in the next lesson.

for number in range(3):
    print(number)

Example

word = "code"
count = 0
for letter in word:
    count += 1
    print(count, letter)

Key points

  • Sequence: a value that holds items in order, like a string or a list.
  • Use for to visit each item in a sequence.
  • The loop variable takes each value in turn.
  • You do not need an index for a simple walk.
  • The loop ends when the sequence runs out of items.

In this example, word holds the text "code". The count starts at 0. The loop takes the first letter, which is c. It adds 1 to count and prints 1 and c. It repeats for o, d, and e. The loop ends when the word runs out of letters.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does the loop variable hold in for letter in "cat": ?