मराठी

Create a class Person to store personal information (of your choice) for a person. Ensure that while accepting the data incorrect entry is properly handled.

Advertisements
Advertisements

प्रश्न

Create a class Person to store personal information (of your choice) for a person. Ensure that while accepting the data incorrect entry is properly handled.

कोड लेखन
Advertisements

उत्तर

The class validates the name, age, and email address before storing them. Invalid input raises a clear ValueError.

class Person:
    def __init__(self, name, age, email):
        name = name.strip()
        email = email.strip()

        if not name:
            raise ValueError("Name cannot be empty.")

        if not isinstance(age, int) or isinstance(age, bool):
            raise TypeError("Age must be an integer.")

        if age < 0 or age > 120:
            raise ValueError("Age must be between 0 and 120.")

        if "@" not in email or "." not in email.split("@")[-1]:
            raise ValueError("Enter a valid email address.")

        self.name = name
        self.age = age
        self.email = email

    def __str__(self):
        return f"Name: {self.name}, Age: {self.age}, Email: {self.email}"


def create_person():
    while True:
        try:
            name = input("Enter name: ")
            age = int(input("Enter age: "))
            email = input("Enter email: ")
            person = Person(name, age, email)
            print("Person created successfully.")
            return person
        except (TypeError, ValueError) as error:
            print("Invalid entry:", error)
            print("Please try again.\n")


person = create_person()
print(person)

The try/except block prevents incorrect entries from crashing the program and repeatedly requests input until valid information is supplied.

shaalaa.com
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 8: Exception Handling & Generate Functions - EXERCISE [पृष्ठ १५८]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 8 Exception Handling & Generate Functions
EXERCISE | Q 16. | पृष्ठ १५८
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×