Rocket has a new job: read every crate name over the station speakers. He types print(cargo[0]), then print(cargo[1]), then print(cargo[2]). The cargo list has twenty items.
"This will take all day," he groans.
Raven reads over his shoulder. "What do you notice about your lines?" she asks. "They are all the same," Rocket says. "Only the index changes."
Nova flies in a little circle, around and around. "Would you like a hint? Python can visit each item for you, one after another."
A for loop visits each item in a list, one at a time. Read this program.
cargo = ["water", "oats", "tools"]
for item in cargo:
print(item) | The screen shows |
|---|
| water |
| oats |
| tools |
| Round | item holds | The screen shows |
|---|---|---|
| 1 | water | water |
| 2 | oats | oats |
| 3 | tools | tools |
| Statement about for loops | True or false? |
|---|---|
| The for line ends with a colon. | ? |
| The loop body is indented. | ? |
| The loop variable must be called item. | ? |
| The loop visits the items from the last one to the first one. | ? |
crew = ["Rocket", "Raven", "Kai"]
for name in crew:
print("Check:", name) tools = ["drill", "tape", "clamp", "rope"]
for t in tools:
print("Pack", t) | Statement about the tools program | True or false? |
|---|---|
| In round 1, t holds "drill". | ? |
| The loop runs 3 times. | ? |
| t holds a new item each round. | ? |
| print runs only once in all. | ? |
Awesome! One loop did the work of many lines. Tomorrow you will find out which lines are inside a loop and which are not.