Check your understanding of the previous reading: creating and indexing a list of dataclasses, the type of the iteration variable, and loop patterns over a list of dataclasses.
Given the following code…
from dataclasses import dataclass
@dataclass
class Shape:
color: str
type: str
size: int
shapes = [Shape("red", "circle", 25),
Shape("blue", "triangle", 30),
Shape("green", "square", 27),
Shape("red", "triangle", 27)]
What will each of the following expressions produce?
When this code is executed, what will be printed?
from dataclasses import dataclass
@dataclass
class Animal:
name: str
type: str
weight: int
zoo = [ Animal("Terry", "Owl", 5),
Animal("Perry", "Giraffe", 80),
Animal("Kerry", "Penguin", 20),
Animal("Harry", "Lion", 50),
Animal("Larry", "Monkey", 30),
Animal("Jerry", "Elephant", 100)
]
result = []
taking = True
for animal in zoo:
if animal.name[1] == 'a':
taking = False
elif taking:
result.append(animal)
biggest = result[0]
for animal in result:
if animal.weight > biggest.weight:
biggest = animal
print(biggest.type)
The first loop is a Take pattern: it appends animals while taking is True, and stops taking at the first name whose second letter is 'a'. Terry, Perry and Kerry are taken; Harry sets taking to False, so Larry and Jerry are never appended. The second loop is a Max pattern over those three animals: the heaviest is Perry (80), so the program prints Perry's type, Giraffe.