Loops Overview
A loop repeats work.
Like singing the same chorus again and again.
Computers love loops because they do not get bored.
Python has two main loops: for and while.
Why loops exist
Without loops you would copy the same lines many times.
That is messy and easy to break.
A loop says, do this pattern for each item, or while a rule is True.
Print every name in a list
Count from 1 to 10
Keep asking until the answer is right
Walk through each letter in a word
for loops in one sentence
A for loop walks through a collection.
One item at a time. Then it stops when the collection ends.
while loops in one sentence
A while loop keeps going while a check is True.
You must change something inside, or it may never stop.
When to pick which
Use for when you know the items or the count.
Use while when you wait for a condition to change.
for: each toy in the box
for: each number in range(5)
while: keep guessing until correct
while: keep adding until the jar is full
break and continue preview
break leaves the loop early.
continue skips the rest of this round and starts the next.
Loops and indent
The body of a loop is indented under the colon.
Same rule as if.
Tip: Next we practice for loops in detail. Then while loops.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.