Python-生成包含某年12个月天数的字典

生成一个包含一年中12个月,每个月天数的字典,调用判断闰年的函数
思路:
1、先用推导字典生成一个含12个月的字典
2、依次判断每个月的天数,对字典values值进行赋值

def leap_year(year):    #判断是否闰年,输入参数可以是字符串的年份或数字的年份
    print('您输入的年份是:',year) #打印输入
    if isinstance(year,int) and year>0:  # 判断是大于0的整数
        if (year%4 == 0 and year%100!=0) or year%400 == 0:
            print('您输入的年份是闰年!')#可注释
            return True  
        else:
            print('您输入的年份不是闰年!') #可注释
            return False
    elif isinstance(year,str):
        if year.isdigit():
            if int(year)>0 and ((int(year)%4 == 0 and int(year)%100!=0) or int(year)%400 == 0):
                print('您输入的年份是闰年!')#可注释
                return True  
            elif int(year)>0:
                print('您输入的年份不是闰年!')#可注释
                return False
        else: 
            print( '输入参数错误')#
            return False
    else:
        print( '输入参数错误')
        return False          

def month_days(year):
    month_day_dict={k:0 for k in range(1,13)} #生成每个月天数的字典
    for k in month_day_dict.keys():
        if k==2 and leap_year(year):
            month_day_dict[2]=29
        elif k==2 and not leap_year(year):
            month_day_dict[2]=28
        elif k in [1,3,5,7,8,10,12]:
            month_day_dict[k]=31
        elif k in [4,6,9,11]:
            month_day_dict[k]=30
    return month_day_dict

运行结果

你可能感兴趣的:(个人python小程序)