繁体   English   中英

if else 循环一个月和几天的问题

[英]problem with if else loop for a month and days problem

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

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

    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

提问方式

您正在检查一个整数是否等于一个集合。 您想检查整数是否集合中。 顺便说一句,你用的set是错误的(这里修复了),二月可能有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模块,该模块修复了二月问题的 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM