CS50 Python pset3

45 Views Asked by At

I'm trying to solve problem outdated where I have to convert "american dates (MM,DD,YYY)" to ISO8601 (YYYY,MM,DD). This is my code:

def main():
    Months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
    ]


    while True:
        Date = input("Please insert a Date: ").strip().title().replace(",", "").replace(" ", "/").split("/")
        try:
            Month = Date[0]
            Day = Date[1]
            Year = Date[2]

            if Month in Months:
                Month = Months.index(Month)+1


            if Day.isalpha() == True:
                pass
            elif int(Day) > 31 or int(Month) > 12:
                pass
            else:
                print(f"{Year}-{int(Month):02}-{int(Day):02}")
                break
        except ValueError:
            pass
main()

There are some constraints, I've solved 9 but there are 2 I consider that should be handled by the program
but as they are expected to fail and re-prompt the user I got stuck. these are the inputs that should fail:

October/9/1701
September 8 1636

Can anyone point me in the right direction

1

There are 1 best solutions below

0
DinoCoderSaurus On

Even though they are handled by the program, they are expected to fail and reprompt at per the spec:

If the user’s input is not a valid date in either format [formatted like 9/8/1636 or September 8, 1636], prompt the user again.

The program needs to verify the input is in one of the specified input formats before it slices and dices into the output format. Have the while loop detect proper input, and then do the formatting. Psuedo-something like:

while True:
    input(adate)
    if date is mm/dd/yy:
       do something
    else if date is Month day, year:
       do something else
    else:
       reprompt

produce the output