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.

Question 1

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)]

1. How many lists are there?

2. How many dataclass instances are there?

3. How many string literal values are there?

Word bank — not all values are used

Question 2

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?

#ExpressionProduces
1 shapes[0].color
2 shapes[-1].type
3 shapes.size[0]
4 Shape.color
5 size[shapes]

Question 3

Given the following code...

from dataclasses import dataclass

@dataclass
class Animal:
    name: str
    type: str
    weight: float

zoo = [ Animal("Terry", "Giraffe", 80.0),
        Animal("Jerry", "Elephant", 100.0),
        Animal("Kerry", "Penguin", 20.0)
]
result = ""
for an_animal in zoo:
    result += an_animal.name
print(result)

What will be the most accurate type of the following variables?

1. an_animal:

2. an_animal.weight:

3. zoo:

4. result:

Word bank — not all values are used

Question 4

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)

Show worked solution

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.