← Back to course
Code Crew G4 / Week 03 / Tuesday
2/6
Week 03 Β· Loop through a list

Tuesday

Inside or outside?
// Visit every item
⏱ about 15 min

Tuesday: Inside or outside?

The shuttle is boarding. Rocket writes a loop that says Ready for each crew member. Then he adds a line that says All aboard.

When he runs it, All aboard shows three times! "Let's see what happens," he mutters, and he looks at the spaces at the start of each line.

Raven points. "What do you notice about the last line? It lines up with the print above it." Nova glows. "Would you like a hint? The spaces at the start of a line tell Python where the loop ends."

Indented lines belong to the loop

Lines that are indented under the for line are inside the loop. They run once for each item.

The first line that is not indented is outside the loop. It runs once, after the loop is done.

crew = ["Rocket", "Raven", "Kai"]
for name in crew:
    print("Ready:", name)
print("All aboard!")
The screen shows
Ready: Rocket
Ready: Raven
Ready: Kai
All aboard!

Rocket had indented the last line. That put it inside the loop, so it ran three times. Moving it back to the left fixed it.

How many times does the program above show All aboard!?
How many lines show on the screen in all?
pods = [4, 6]
for p in pods:
    print("Check pod", p)
    print(p * 2)
print("Done")
PUT THE SCREEN LINES IN THE ORDER THE PROGRAM ABOVE SHOWS THEM
  • ?12
  • ?8
  • ?Check pod 4
  • ?Check pod 6
  • ?Done
WHY THIS EXERCISEThe whole loop body runs each round, in order, before the next round starts.
WHAT IF IT MOVED?
  • Read the question.
  • Tap your answer.
In the crew program above, suppose print("All aboard!") is indented. How many times does it show?
Try it
Clap once for each finger on one hand. That is the loop.
Then say Done one time. That is the line after the loop.

Practice lab: open the bays

bays = ["A", "B", "C"]
for b in bays:
    print("Open", b)
print("Bays ready")
print("Count:", len(bays))
How many lines show on the screen in all?
How many times does Bays ready show?
What number shows after Count:?
INSIDE OR OUTSIDE?
  • Read the question.
  • Tap your answer.
Which line is inside the loop?
A loop has 4 items, and a print is indented under it. How many times does that print run?
A print has no indent and comes after the loop. When does it run?
StatementTrue or false?
Indented lines run once for each item.?
A line with no indent after the loop runs once.?
Indents do not matter in Python.?
A loop body can have more than one line.?
WHY THIS EXERCISEIn Python, indents are part of the code. They decide what repeats.
A loop over 3 items has two indented print lines. How many lines show from the loop?
WHY THIS EXERCISEThe whole body runs each round, so 2 lines times 3 rounds makes 6.

You can read loops like a pro now. Tomorrow a loop will help Rocket add up the fuel.

← Monday