English

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

Question

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).

Code Writing
Advertisements

Solution

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
  Is there an error in this question or solution?
Chapter 8: Exception Handling & Generate Functions - EXERCISE [Page 158]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 8 Exception Handling & Generate Functions
EXERCISE | Q 15. | Page 158
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×