python 3 100道基础练习题002

题目:某年某月某日,判断这一天是这一年的第几天?

参考代码:

# coding=utf-8
date = input("请输入年月日,格式:'xxxx-xx-xx' \n").strip()
# 省略了输入合法性校验,年必须四位数,月和日必须两位数
year = int(date[0:4])
# 判断是否是闰年,闰年多一天
leap_year = 0
if ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):
leap_year = 1
# 每月的天数列表
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month = int(date[5:7])
day = int(date[8:10])
total = 0
# 前month-1个月的总天数加本月的天数(如果月份大于2加leap_year)就是总天数
for i in range(month - 1):
total += days[i]
total = total + day
if month > 2:
total = total + leap_year
print("%s是本年的第%d天" % (date, total))


 

上一篇:练习7-9 计算天数 (15 分)


下一篇:EF常用命令