Editor

Predict the Output: Coercion Behavior

Advanced · Predict the output · from Python Pydantic: Validate Data Like a Pro

From the lesson: Python Pydantic: Validate Data Like a Pro

Every application deals with messy data. User forms with missing fields, API responses with wrong types, config files with invalid values. Data validation is the practice of checking that data matches your expectations before you use it.

Read the lesson

Read the code carefully and predict exactly what it prints.

from dataclasses import dataclass

@dataclass
class Score:
    value: float
    label: str

    def __post_init__(self):
        self.value = float(self.value)
        self.label = str(self.label).upper()
        if self.value > 100:
            self.value = 100.0

s1 = Score(value="85", label="math")
s2 = Score(value=150, label="science")
print(f"{s1.label}: {s1.value}")
print(f"{s2.label}: {s2.value}")
from dataclasses import dataclass
@dataclass
class Score:
value: float
label: str
def __post_init__(self):
self.value = float(self.value)
self.label = str(self.label).upper()
if self.value > 100:
self.value = 100.0
s1 = Score(value="85", label="math")
s2 = Score(value=150, label="science")
print(f"{s1.label}: {s1.value}")
print(f"{s2.label}: {s2.value}")

More Pydantic exercises

All Python exercises · 50 practice problems · Advanced Python quiz