Lesson 4 homework
One program, grown four times. You'll start from the names list in the lesson and turn it into a little roster manager — a tool that prints the team, adds players, removes them, and swaps them out. Each problem is the last one plus one new idea.
Work like a programmer on each one:
- Write the pseudocode in English first
- Run it in your head before you run it in Python
-
Translate line by line — every piece is something from the lesson or the reading
-
Make as many mistakes as you like
- Don't give up
Start every problem from this list:
Problem 1 — number the roster
Print every player with its index in front, so you can see the position numbers you'll need later.
Output
Code
- This is the "watch the numbers change" loop from the end of the lesson:
for i in range(len(names)) - Inside, print two things on one line — the index
iandnames[i]. Commas inprintput a space between them for free
Problem 2 — add and remove, safely
Ask the user for a name to add, then a name to remove. Print the whole list after each change.
Output (the user typed mo, then tom)
player to add: mo
['scott', 'rish', 'tom', 'jerry', 'john', 'mo']
player to remove: tom
['scott', 'rish', 'jerry', 'john', 'mo']
Code
inputgets the name,appendadds it,removedeletes it — all straight from the lesson- One trap:
removecrashes if the name isn't in the list (you saw theValueErrorin the reading). Guard it — only removeif the name in names, otherwise print something friendly likeno such player - Bonus: guard the add the same way, so you don't append a name that's already on the team
Problem 3 — swap a player
Ask the user for an index and a new name, then replace the player at that index. Print the list.
Output (the user typed 2, then tommy)
Code
- Changing an item in place is
names[i] = new_name— the mutable-list idea from the reading - Remember
inputgives a string; the index has to be a number, soint(...)it — like the calculator in Lesson 1 - Guard the index with
len, exactly like the lesson: only swapif the index < len(names), otherwise printno such index. A careless9should print a message, not crash
Problem 4 — the roster table (stretch)
Give every player a jersey number by turning the roster into a list of lists:
Ask the user for an index and print a sentence about that player.
Output (the user typed 1)
Code
- Each row is itself a list, so you index twice:
players[i][0]is the name,players[i][1]is the number - Build the sentence with an f-string from the Lesson 3 reading:
f"{players[i][0]} wears number {players[i][1]}" - Guard the index with
lenagain — same safe habit as Problem 3
When all four run, look at them side by side: one list, and a whole tool built out of the handful of moves from this week — loop, append, remove, names[i] = ..., and a len guard on every risky reach. That's a real program.