← Python from Scratch Lesson 29 of 78 · 10 XP

The for loop

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

for goes through items one at a time: the characters of a string, the items of a list and much more.

for letter in "cat":
    print(letter)        # c, a, t

for name in ["Anya", "Borya", "Vika"]:
    print("Hello,", name)

The variable after for (here letter, name) gets the next item on each step. Choose a clear name.

A common trick is a counter: create a variable before the loop and increase it inside.

count = 0
for ch in "banana":
    if ch == "a":
        count += 1
print(count)   # 3

When to use for and when while? If you're going through something that already exists — for. If you repeat "until something happens" — while.

Task. Read a string and print the number of vowels in it. Count the letters aeiou in any case as vowels.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.