Python每日一练——第5天:闰年问题升级版

265 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 18 天,点击查看活动详情

1. 问题描述

输入年月日,输出该日期是否是闰年,并且输出该日期是此年份的第几天
闰年判断条件(两个条件满足任意一个就为闰年):

  • 一、能被4整除,并且不能被100整除
  • 二、能被400整除

小伙伴们看了问题描述后,一定要自己先练习,再去看博主的代码和解题思路,才能提高自己的编程水平,全靠自觉哟!!!
欢迎小伙伴们把自己的思路或答案在评论区留言,博主会选一个最优解答进行置顶。

在这里插入图片描述

2. 算法思路

1.接收用户输入的年月日,创建保存12个月份天数的列表
2.根据年份判断是否是闰年,如果是把二月份设为29天,否则把二月份设为28天
3.根据月份和日期统计是当年的第几天

3. 代码实现

实现代码📝:

"""python每日一练:闰年问题升级版
1.接收用户输入的年月日,创建保存12个月份天数的列表

2.根据年份判断是否是闰年,如果是把二月份设为29天,否则把二月份设为28天

3.根据月份和日期统计是当年的第几天
"""

# 1. 接收用户输入的年月日,创建保存12个月份天数的列表
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
day = int(input("请输入日期:"))
# 12个月天数列表
date_list = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
count_day = day  # 用来统计第几天

# 2. 根据年份判断是否是闰年,如果是把二月份设为29天,否则把二月份设为28天
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    print("%s 年是闰年" % year)
    date_list[1]  = 29
else:
    print("%s 年是平年" % year)
    date_list[1] = 28

# 3. 根据月份和日期统计是当年的第几天
for i in range(month - 1):
    count_day += date_list[i]
# 格式化输出
print("%s年:%s月:%s日是当年的第%s天" % (year, month, day, count_day))

运行结果👇:

在这里插入图片描述

在这里插入图片描述

4. 算法升级

使用time模块的strftime函数判断第几天

实现代码📝:

import time

try:
    # 键盘输入日期格式
    a = input('请输入日期(格式:xxxx-xx-xx):')
    # 时间字符串转化为元组
    b = time.strptime(a, '%Y-%m-%d')
except ValueError:
    print('请输入正确的日期格式!')
else:
    b = time.strptime(a, '%Y-%m-%d')  # 时间元组格式化输出
    # print(b)
    # time.struct_time(tm_year=2020, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=1, tm_isdst=-1)
    year = b.tm_year
    month = b.tm_mon
    day = b.tm_mday
    count_day = b.tm_yday  # 一年内的一天(001-366)

    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        print("%s 年是闰年" % year)
    else:
        print("%s 年是平年" % year)

    print("%s年:%s月:%s日是当年的第%s天" % (year, month, day, count_day))

运行结果👇: 在这里插入图片描述