Editor

Add Age Validation with a Setter

Intermediate · Write the code · from Python @property: Getters, Setters, and Computed Attributes

From the lesson: Python @property: Getters, Setters, and Computed Attributes

Imagine a thermostat on your wall. You set the temperature to 72°F and the system heats your house. But what if someone sets it to 5000°F? The house wouldn't literally reach that temperature, but your heating system would run forever trying. A smart thermostat would reject that value immediately.

Read the lesson

Create a class Student with a name (regular attribute) and an age property. The age setter should raise a ValueError with the message 'Age must be between 0 and 150' if the value is outside that range. Use the setter inside __init__. Then create a Student('Bob', 20), print their age, update it to 21, and print again.

# Create the Student class with age validation

More @property exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz