本文共 1382 字,大约阅读时间需要 4 分钟。
输入一个年份判断,判断年份是否为闰年
1、满足闰年的条件有两种
2、一种是世纪闰年能被400整除
3、一种是普通闰年能被4整除同时不能被100整除
通过多重if else进行条件判断
程序如下
year = int(input("输入一个年份: "))if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} 是闰年".format(year)) # 整百年能被400整除的是闰年 else: print("{0} 不是闰年".format(year)) else: print("{0} 是闰年".format(year)) # 非整百年能被4整除的为闰年else: print("{0} 不是闰年".format(year))
运行结果
输入一个年份: 20002000 是闰年输入一个年份: 20202020 是闰年输入一个年份: 21002100 不是闰年
通过多条件的逻辑运算在解法1的基础上进行优化
程序如下
year = int(input("请输入一个年份:"))if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0: print("{0}是闰年".format(year))else: print("{0}不是闰年".format(year))
运行结果
请输入一个年份:20082008是闰年请输入一个年份:20102010不是闰年输入一个年份: 20002000 是闰年
判断一个区间内的年份有多少个闰年,并将闰年都列出来
核心程序就是判断闰年
程序如下:
def isLeapYear(year): if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0: return True else: return False count = 0leapYear=[]for i in list(range(1900,2020,1)): if isLeapYear(i): count += 1 leapYear.append(i)print("闰年个数有 %d 个:"%count)print("这%d个闰年分别是:"%count)print(leapYear)
运行结果:
闰年个数有 29 个:这29个闰年分别是:[1904, 1908, 1912, 1916, 1920, 1924, 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016]
还有更多的方法,欢迎大家留言一起探讨学习
转载地址:http://vrhaf.baihongyu.com/