Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

Outdated - CS50's Introduction to Programming with Python: Code does not break

$
0
0

I'm using the CS50's tutorials to teach myself python. I am trying to solve the 'Outdated' problem in problem set 3. The code works when I input date as 9/8/1636(i.e., correctly transforms date to yyyy-mm-dd and outputs the result) but not when I input September 8, 1636; it again prompts me for input. I cannot figure out where I went wrong.

The context to the problem can be found here, and the code i tried is copied below:

# Initiate the listmonth_li = ["January","February","March","April","May","June","July","August","September","October","November","December"]# Start infinite loop that breaks when a valid date is enteredwhile True:    # Prompt the user for a date (format: 9/8/1636 or september 8, 1636)    input_date = input("Date (in month/day/year order): ").strip()    # Attempt to transform date into yyyy-mm-dd format    try:        # Split month, day and year by "/" separator and convert to integer        month, day, year = map(int, input_date.split("/"))        # Check whether month and day fall within expected ranges        if 1 <= month <= 12 and 1 <= day <= 31:            # If so, then print year, month, and date            print(year,f"{month:02}",f"{day:02}", sep = "-")            # Break out of the loop            break        else:            # Check if date string starts not with a number but a letter            if not input_date[0].isdigit():                # Split the date by space                month, day, year = input_date.split(" ")                # A comma (,) will remain, so need to get rid of that                day = day.replace(',', '')                # Convert day and year to integers; will deal with month after                day = int(day)                year = int(year)                # Capitalize month for case insensitivity                month = month.capitalize()                # Need to check if the month exists in the list                if month in month_li and (1 <= day <= 31):                    print(year,f"{month_li.index(month) + 1:02}", f"{day:02}", sep = "-")                    break    except:        pass

Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>