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."
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.
pods = [4, 6]
for p in pods:
print("Check pod", p)
print(p * 2)
print("Done") bays = ["A", "B", "C"]
for b in bays:
print("Open", b)
print("Bays ready")
print("Count:", len(bays)) | Statement | True 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. | ? |
You can read loops like a pro now. Tomorrow a loop will help Rocket add up the fuel.