通过四种方法(元组、列表、集合、字典)计算输入日期是当年的第几天
import datetime
def if_leap_year(year):
'''
判断是否是闰年
'''
leap_year = False
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
leap_year = True
return leap_year
def which_day_tup(year,month,day):
'''
元组
'''
year_tup = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
days = sum(year_tup[:month-1])+day
if if_leap_year(year) :
print("这一天是当年的第{}天".format(days+1))
else:
print("这一天是当年的第{}天".format(days))
def which_day_list(year, month, day):
'''
列表
'''
year_list = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if if_leap_year(year):
year_list[1] = 29
days = sum(year_list[:month-1])+day
print("这一天是当年的第{}天".format(days))
def which_day_set(year,month,day):
'''
集合
'''
_30days_month = {4,6,9,11}
_31days_month = {1,3,5,7,8,10,12}
days = 0
days += day
for i in range(1,month):
if i in _30days_month:
days += 30
elif i in _31days_month:
days += 31
else :
if if_leap_year(year):
days += 29
else:
days += 28
print("这一天是当年的第{}天".format(days))
def which_day_dict(year,month,day):
'''
字典
'''
days=0
days += day
years_dict = {1:31,
2:28,
3:31,
4:30,
5:31,
6:30,
7:31,
8:31,
9:30,
10:31,
11:30,
12:31 }
for i in range(1,month):
days += years_dict[i]
if if_leap_year(year) and month >2:
days += 1
print("这一天是当年的第{}天".format(days))
def main():
conntiue = input("是否继续(y/n):")
while conntiue == "y":
input_date_str = input("请输入日期 yyyy/mm/dd:")
input_date = datetime.datetime.strptime(input_date_str,'%Y/%m/%d')
year = input_date.year
month = input_date.month
day = input_date.day
which_day_tup(year,month,day)
which_day_list(year,month,day)
which_day_set(year, month, day)
which_day_dict(year, month, day)
print()
conntiue = input("是否继续(y/n):")
if __name__ == '__main__':
main()