CS50 Python pset3

问题描述 投票:0回答:1

我正在尝试解决过时的问题,我必须将“美国日期(MM,DD,YYY)”转换为ISO8601(YYYY,MM,DD)。 这是我的代码:

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()

有一些限制,我已经解决了 9 个,但我认为有 2 个应该由程序处理
但由于预计它们会失败并重新提示用户,我陷入了困境。 这些是应该失败的输入:

October/9/1701
September 8 1636

任何人都可以指出我正确的方向吗

python cs50
1个回答
0
投票

程序需要验证输入是否采用指定的输入格式之一,然后将其切片和切块为输出格式。让 while

 循环检测正确的输入,然后进行格式化。伪-类似:

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
    
© www.soinside.com 2019 - 2024. All rights reserved.