Python每日一练——第5天:闰年问题升级版
前言📢📢
Python每日一练来啦,本文已收录于:
此专栏目的在于,帮忙学习Python的小白提高编程能力,训练逻辑思维,每周持续更新中,欢迎免费订阅!!!
1. 问题描述
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))
运行结果👇:
《100天精通Python从入门到就业》专栏推荐白嫖80gPython全栈视频
:本专栏专门针对零基础和需要进阶提升的同学所准备的一套完整教学,从0到100的不断进阶深入,后续还有实战项目,轻松应对面试,专栏订阅地址:
