一、题目
给定一个年份,判断这一年是闰年还是平年
输入:
输入一个要判断的年份,且为正整数。
输出:
输出一行,如果给定的年份是闰年,则输出“闰年”,否则输出“平年”。
二、样例
输入:
1999
输出:
平年
输入:
2024
输出:
闰年
数据规模与约定
1990 <= y <= 2050
三、解析
判断该年份是闰年还是平年,有两种方法:
- 通过判断某一年的二月份是否有29天来确定该年是闰年还是平年
- 最经典的方法:
①如果年份能被4整除但不能被100整除,则是闰年。
②如果年份能被100整除但同时也能被400整除,则是闰年。
③其他情况则为平年。
四、代码实现
解法一:
import datetime
year = int(input("请输入查询的年份:")) # 输入
time_delta = datetime.timedelta(days=1) # 存储时间的变化量
dt = datetime.date(year=year, month=3, day=1) # 指定输入年份的3月1号
res = dt - time_delta # 让dt存储的日期往前走一天
if res.day == 29: # 如果那年的2月份有29天,则为闰年
print('闰年')
else:
print('平年')
解法二:
years = int(input("请输入查询的年份:"))
if (years % 4 == 0 and years % 100 != 0) or (years % 100 == 0 and years % 400 == 0):
print('闰年')
else:
print('平年')
运行结果:
由于上方代码未设置输入范围,现进行代码优化如下:
代码优化:
import sys
years = int(input("请输入查询的年份:"))
while (years >= 0 and years <= 2050):
if (years % 4 == 0 and years % 100 != 0) or (years % 100 == 0 and years % 400 == 0):
print("闰年")
else:
print("平年")
sys.exit()
print("查询年份不规范")
五、总结
- 要使用现实时间,需导入Python内置的datetime模块,以便在程序中使用日期和时间相关的函数和类。
- python中not、and、or的优先级由高到低分别为:not、and、or。
- sys.exit():不需要考虑平台等因素的影响,一般是退出Python程序的首选方法,需引入 Python内置的 sys 模块 import sys。