The for Loop
Loops and lists belong together. With a while loop, you could go through the indexes of a list, from 0 to the last one, and read each element:
games = ["Football", "Tennis", "Golf"]
index = 0
while index < len(games):
print(games[index])
index += 1This prints:
Football
Tennis
GolfIt works, but you have to look after the index yourself. Going through all the elements of a list is so common that Python has a simpler loop for it, for:
games = ["Football", "Tennis", "Golf"]
for game in games:
print(game)Football
Tennis
GolfRead it as “for each game in games”. In each iteration, the variable game holds the next element of the list: first "Football", then "Tennis" and then "Golf". After the last element, the loop ends. You don't need an index or len() at all, so you can't get them wrong either.
The line with for creates the variable game for you, and its name is up to you: for x in games: works the same. A good habit is to name it after one element of the list: game in games, name in names, price in prices. Then the code reads almost like a sentence.
A common slip is to print the list instead of the element inside the loop:
games = ["Football", "Tennis", "Golf"]
for game in games:
print(games)['Football', 'Tennis', 'Golf']
['Football', 'Tennis', 'Golf']
['Football', 'Tennis', 'Golf']The loop still runs three times, but each time it prints the whole list. Inside the loop, use the element: game, not games.
Like if and while, the line with for ends with a colon. Without it, Python stops with SyntaxError: expected ':'.
Instructions
Write a for loop that prints each element of the teammates list on its own line.
Below it, write a second loop that prints the teammates with their numbers: 1. Zack, 2. Nick, 3. Matthew and 4. Emily. Before the loop, create a variable number with the value 1. In the loop, print the number and the name with an f-string, for example f"{number}. {teammate}", and then increase number by 1.