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
या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
