0
months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
]

while True:
    user_input = input("Date: ")
    parts = user_input.split("/")
    if len(parts) == 3:
       
        month, day, year = parts
        try:
            month = int(month)
            day = int(day)
            year = int(year)
            if 1 <= month <= 12 and 1 <= day <= 31:
                break
        except ValueError:
            pass
    else:
       
        parts = user_input.split()
        if len(parts) == 3:
            month_name, day, year = parts
            try:
                month = months.index(month_name) + 1
                day = int(day.strip(","))
                year = int(year)
                if 1 <= month <= 12 and 1 <= day <= 31:
                    break
            except (ValueError, IndexError):
                pass

    print("Invalid date format. Please try again.")

print(f"{year}-{month:02}-{day:02}")

Here’s the code. And the issue is when I input

September 8 1636

I should’ve got the invalid error but it’s reprompting, here’s the output:

Date: September 8 1636
1636-09-08

Need help to fix this.

1 Answer 1

1

In your else: block, you split user_input on spaces, but don't verify there is a comma after the day of the month (see line parts = user_input.split()). Then you strip the expected comma from day (see line day = int(day.strip(","))). I bet you expect an error if there isn't a comma. However, it works fine when the comma is missing. Surprise! :-) So, you need to check user_input and verify it is in the expected format of Month dd, yyyy WITH THE COMMA!

2
  • Thanks for helping Commented Jan 26, 2023 at 13:18
  • Glad it helped. Did it answer your question? If so please check the answer to accept so others know it's a useful answer in the future.
    – kcw78
    Commented Jan 26, 2023 at 19:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .