我正在用CS50的S教程自学Python .我正在try 解决问题集3中的过时问题.当我输入日期9/8/1636年(即,正确地将日期转换为yyyy-mm-dd并输出结果)时,代码起作用;但当我输入1636年9月8日时,代码不起作用;它再次提示我输入.我想不出哪里出错了.

问题的上下文可以在here处找到,我try 的代码复制如下:

# Initiate the list
month_li = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
]

# Start infinite loop that breaks when a valid date is entered
while 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

推荐答案

看看发生了什么.当您输入该字符串时,map(int...将抛出异常.这将跳到您的except,它什么也不做,并循环再次请求输入.你永远不会忘记那句话.

您应该做的是go 掉try/Except,并将if not input_date[0].isdigit()移到前面.这样,您就不会try 解析错误数据.

while True:
    input_date = input("Date (in month/day/year order): ").strip()
    if not input_date[0].isdigit():
        # Split the date by space
        month, day, year = input_date.split(" ")
        ...
    else:
        # Split month, day and year by "/" separator and convert to integer
        month, day, year = map(int, input_date.split("/"))

Python相关问答推荐

从今天起的future 12个月内使用Python迭代

symy.分段使用numpy数组

查找下一个值=实际值加上使用极点的50%

如何使用Python中的clinicalTrials.gov API获取完整结果?

Python -根据另一个数据框中的列编辑和替换数据框中的列值

GL pygame无法让缓冲区与vertextPointer和colorPointer一起可靠地工作

我从带有langchain的mongoDB中的vector serch获得一个空数组

使用FASTCGI在IIS上运行Django频道

对某些列的总数进行民意调查,但不单独列出每列

沿着数组中的轴计算真实条目

对于一个给定的数字,找出一个整数的最小和最大可能的和

django禁止直接分配到多对多集合的前端.使用user.set()

Python虚拟环境的轻量级使用

如何在python polars中停止otherate(),当使用when()表达式时?

driver. find_element无法通过class_name找到元素'""

使用Python查找、替换和调整PDF中的图像'

使用__json__的 pyramid 在客户端返回意外格式

解决Geopandas和Altair中的正图和投影问题

PYTHON中的pd.wide_to_long比较慢

类型对象';敌人';没有属性';损害';