Lecture Atlas

//week-05

EGD103

//concept

Directly supported

Python For-Loops

medium coding-assignment exam

What this means

A for-loop repeats an action over each item in a sequence — a list, a string, a range, or any iterable.

When to use it

When you already have a collection you want to walk through. Reach for while instead when you don’t know in advance how many iterations you need.

Example

for character in "hello":
    print(character)

Common mistake

Overwriting your result inside the loop instead of accumulating it:

total = 0
for n in [1, 2, 3]:
    total = n   # wrong — overwrites total each iteration

The fix is total = total + n.

Tiny practice

Write a loop that counts how many vowels are in a word.