Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Validate Basic Constructor Inputs

Create a class that validates its constructor arguments and provides a simple is_valid method.

Python practice15 minClasses & Objects FundamentalsIntermediateLast updated April 7, 2026

Problem statement

Define a Person class with a constructor that accepts name and age. The class should validate the inputs according to these rules: - name must be a string containing at least one non-space character. - age must be an integer between 0 and 120 inclusive. The constructor should store the inputs and a cached validity state. Provide an is_valid() method that returns True when both fields meet the rules and False otherwise. Do not raise exceptions for invalid inputs; the object should still be constructible but report validity via is_valid().

Task

Implement a Person class whose constructor records inputs and validates them according to clear rules. Provide an is_valid() method that reports whether the constructed object meets the validation requirements.

Examples

Valid person

Input

Person('Alice', 30).is_valid()

Output

True

Name is a non-empty string and age is an integer within [0, 120].

Input format

A constructor call Person(name, age). Then call methods like is_valid() to check state.

Output format

Expressions return Python values. For validation checks return a boolean from is_valid().

Constraints

- name must be a string and not purely whitespace. - age must be an int and 0 <= age <= 120. - The constructor must not raise for invalid inputs; use is_valid() to report validity.

Samples

Sample 1

Input

Person('Bob', 0).is_valid()

Output

True

Age 0 is allowed (lower bound).