Looping Through a List ๐
You already know for loops with range(). Here's the even better trick:
you can loop straight over a list and get each item, one at a time.
pets = ["cat", "dog", "fox"]
for pet in pets:
print(f"I love my {pet}!")
Output:
I love my cat!
I love my dog!
I love my fox!
The loop runs once for every item. Each time around, the variable pet
holds the next thing in the list. You pick that variable's name โ it
could be pet, thing, or banana. Pick something that makes sense!
No range(), no counting, no positions. Just "for each thing in the list".
Your mission
- Make a list called
planetswith at least 4 planets in it - Use a
forloop to print one sentence per planet - Each sentence must include that planet's name โ use an f-string!
Your code
Press โถ Run to see what your code does!