首页 > 解决方案 > problem with if else loop for a month and days problem

问题描述

why do I get the wrong output for the code below, I've put the output below

(some might suggest using date-time module, I'm going with this method due to some complications with the main program)

    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)

I get this output

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

标签: pythonfor-loopif-statement

解决方案


Question approach

You are checking if an integer is equal to a set. You want to check if the integer is in the set. By the way, the sets you use are wrong (fixed here) and february may have 29 days (not fixed in this solution).

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 approach

Another solution is to use the calendar module which fixed the 29 days on february issue.

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

推荐阅读