For Loops
A for loop visits each item in a group.
Like walking down a row of lockers and opening each one.
You write for, a name for the current item, in, then the group.
Then indent the steps to do for that item.
Loop over a list
The loop variable holds one item at a time.
You pick the name. pet, fruit, n, anything clear.
Loop over a string
A string is a row of characters.
for can visit each letter.
range for counting
range makes a stream of numbers.
range(5) gives 0, 1, 2, 3, 4
range(1, 5) gives 1, 2, 3, 4
range(0, 10, 2) gives 0, 2, 4, 6, 8
The stop number is not included
enumerate for index and item
enumerate gives the place number and the item together.
Helpful when you need both.
break and continue
break stops the whole loop.
continue skips to the next item.
Nested for loops
A loop inside a loop is like shelves inside a cabinet.
The outer loop picks a shelf. The inner loop walks that shelf.
Tip: Name the loop variable after what it holds. Clear names make loops easy to read.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.