当时老师让我们做这道题是想锻炼我们的“选择循环方法”,所以用选择循环方法:
第一种方法解析:1,3,5,7,8,10,12三十一天永不差,其余是30天,2月是28天(闰年是29天)
先假设每一个月都是30天,然后再计算有几个31天和28(或29天)的月份
1-2月是一个计算段,3-7是一个计算段,8-12是一个计算段
date = input('输入某年某月某日,格式为:****-**-**,小于10请写0*:')
# 使用切片截取年,月,日
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:])
# 判断是否是闰年,并为每一月赋值
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
feb = 29
else:
feb = 28
# 1-2月是一个计算段,3-7是一个计算段,8-12是一个计算段
result = 0
if feb == 29:
if 1 <= month <= 2:
result = (month - 1) * 30 + day + int(month / 2)
elif 2 < month <= 7:
result = (month - 1) * 30 + day + int(month / 2) - 1
elif 12 >= month > 7:
result = 213 + (month - 8) * 30 + day + int((month - 7) / 2)
elif feb == 28:
if 1 <= month <= 2:
result = (month - 1) * 30 + day + int(month / 2)
if 2 < month <= 7:
result = (month - 1) * 30 + day + int(month / 2) - 2
elif 12 >= month > 7:
result = 212 + (month - 8) * 30 + day + int((month - 7) / 2)
print('{}-{}-{}是一年中的第{}天'.format(year, month, day, result))
上面是我自己写的代码,然后我查阅了一下其他人写的,顿时发现我写的好low
第二种方法解析一年12个月份放入列表中,其中二月特殊表示(闰年29天,其他28天),
代码date = input('输入某年某月某日,格式为:****-**-**,小于10请写0*:')
# 使用切片截取年,月,日
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:])
# 判断是否是闰年,并为每一月赋值
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
feb = 29
else:
feb = 28
date1 = [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
res = 0
i = 0
for i in date1[0:month - 1]:
res = res + i
res += day
print('{}-{}-{}是一年中的第{}天'.format(year, month, day, res))
第三种方法,如果配合Python中的 calendar 标准库,可以把判断闰年的一长串代码直接用isleap()函数代替
代码
import calendar
if calendar.isleap(year):
feb = 29
else:
feb = 28
date2 = [31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
res = 0
i = 0
for i in date2[0:month-1]:
res = res + i
res += day
print('{}-{}-{}是一年中的第{}天'.format(year, month, day, res))
结果



