28. Many objects together — Homework solutions
Solution files are in exercises/28/homework/solutions/.
All four use the same small Hero class from each starter
file's top.
Problem 1 — A party of heroes
Problem. Build a list of three heroes and print each one.
Worked solution.
party = [
Hero("Ada", 100),
Hero("Ben", 80),
Hero("Cara", 120),
]
for h in party:
print(f"{h.name}: {h.hp} HP")Output:
Ada: 100 HP
Ben: 80 HP
Cara: 120 HP
Problem 2 — Total HP
Problem. Add up everyone's HP.
Worked solution.
total = 0
for h in party:
total = total + h.hp
print(f"Team HP: {total}") # Team HP: 300The accumulate pattern from Chapter 20, reading a field instead of a plain number.
Problem 3 — Who is hurt?
Problem. Print every hero whose hp is
below their max_hp.
Worked solution.
for h in party:
if h.hp < h.max_hp:
print(f"{h.name} is hurt.")Only heroes who took damage print. The if compares two
fields of the same object.
Challenge — Strongest hero
Problem. Find the hero with the most HP.
How to think about it. Accumulate a maximum: keep a
variable for the best hero so far, replacing it whenever a stronger one
appears. Start it as the first hero (or None, filled on the
first turn).
Worked solution.
strongest = party[0]
for h in party:
if h.hp > strongest.hp:
strongest = h
print(f"Strongest: {strongest.name}") # Strongest: CaraCommon mistakes.
- Starting
strongestatNone, then writingh.hp > strongest.hpon the first turn raises anAttributeErrorbecauseNonehas no.hp. Start with the first hero, or guard the first turn.
Done?
You can now manage a whole collection of objects with loops you already know. Next, Inheritance in depth lets one class build on another, so shared behaviour is written once.