Check a date

Use the Gregorian calendar with positive integer years. Months are 1 to 12; days start at 1. A leap year is divisible by 4, except a year divisible by 100 must also be divisible by 400.

Write a function that takes three integers as input representing a date (day, month, year) and returns

  • "Valid" if the date is valid, or
  • "Invalid", otherwise.

Make sure you consider leap years!

Complete Listing 1. Save the completed code as check_date_validity.py and run it to check the supplied assertions.

Listing 1: Starter function and checks for check_date_validity.
def check_date_validity(day: int, month: int, year: int) -> str:
    # Check that the year is valid.
    # Check whether the month is valid.
    # If the month has 30 days, check whether day <= 30.
    # If the month has 31 days, check whether day <= 31.
    # If the month is February and the year is a leap year, check day <=
    # 29.
    # If the month is February and the year is not a leap year, check
    # day <= 28.
    raise NotImplementedError("Replace this line with your code.")


# Last day of a 31-day month
got = check_date_validity(31, 12, 2023)
assert got == "Valid", f"31/12/2023: expected 'Valid', got {got!r}"

# February in a leap year: 29 days
got = check_date_validity(29, 2, 2024)
assert got == "Valid", f"29/2/2024: expected 'Valid', got {got!r}"

# One day past the end of February, even in a leap year
got = check_date_validity(30, 2, 2024)
assert got == "Invalid", f"30/2/2024: expected 'Invalid', got {got!r}"

# Your cases: February in a common year, a 30-day month, month 13?
# got = check_date_validity(___, ___, ___)
# assert got == "___", f"___: expected '___', got {got!r}"
  • assert condition checks a Boolean condition. A true condition produces no output; a false condition raises AssertionError. For example, assert 2 + 3 == 5 passes.
  • a % b returns the remainder after division by nonzero b. For example, 7 % 3 is 1, and 12 % 4 is 0.