हिंदी

Write a program, to accept a date as day, month and year from user and raise appropriate error(s), if legal value(s) is not supplied. Display appropriate message till user inputs correct value(s).

Advertisements
Advertisements

प्रश्न

Write a program, to accept a date as day, month & year from user and raise appropriate error(s), if legal value(s) is not supplied. Display appropriate message till user inputs correct value(s).

कोड लेखन
Advertisements

उत्तर

The program uses ValueError for non-numeric input and for dates that do not exist, such as 31 February.

from datetime import date

while True:
    try:
        day = int(input("Enter day: "))
        month = int(input("Enter month: "))
        year = int(input("Enter year: "))

        if year < 1:
            raise ValueError("Year must be positive.")

        valid_date = date(year, month, day)
        print("Valid date:", valid_date.strftime("%d-%m-%Y"))
        break

    except ValueError as error:
        print("Invalid date:", error)
        print("Please enter the date again.\n")

datetime.date() automatically checks the number of days in each month and leap-year rules.

shaalaa.com
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 8: Exception Handling & Generate Functions - EXERCISE [पृष्ठ १५८]

APPEARS IN

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

Englishहिंदीमराठी


      Forgot password?
Use app×