【问题标题】:problem with if else loop for a month and days problemif else 循环一个月和几天的问题
【发布时间】:2020-09-08 05:15:05
【问题描述】:

为什么我得到下面代码的错误输出,我把输出放在下面

(有些人可能会建议使用日期时间模块,由于主程序有些复杂,我将使用此方法)

    months = [1,2,3,4,5,6,7,8,9,10,11,12]
    for month in months:
        if month == {1,3,5,7,9,11}:
            days= 31
            print(days)
        elif month == {4,6,8,10,12}:
            days = 30
            print(days)
        else :
            days = 28
            print(days)

我得到这个输出

    28
    28
    28
    28
    28
    28
    28
    28
    28
    28
    28
    28

【问题讨论】:

    标签: python for-loop if-statement


    【解决方案1】:

    问题方法

    你正在检查一个整数是否等于一个集合。您想检查整数是否集合中。顺便说一句,你使用的套数有误(此处已修复),2 月可能有 29 天(此解决方案中未修复)。

    for month in range(1, 13):
        if month in {1, 3, 5, 7, 8, 10, 12}:
            days = 31
        elif month in {4, 6, 9, 11}:
            days = 30
        else :
            days = 28
        print(f"{month:2}: {days}")
    
     1: 31
     2: 28
     3: 31
     4: 30
     5: 31
     6: 30
     7: 31
     8: 31
     9: 30
    10: 31
    11: 30
    12: 31
    

    日历方法

    另一种解决方案是使用calendar 模块,该模块修复了 2 月发行的 29 天。

    import calendar
    
    
    for month in range(1, 13):
        days = calendar.monthrange(2020, month)[1]
        print(f"{month:2}: {days}")
    
     1: 31
     2: 29
     3: 31
     4: 30
     5: 31
     6: 30
     7: 31
     8: 31
     9: 30
    10: 31
    11: 30
    12: 31
    

    【讨论】:

      猜你喜欢
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多