题目:
输入年月日,计算该天是本年的第几天。
例如1990年9月20日是1990年的第263天,2000年5月1日是2000年的第122天。
(闰年:能被400整除,或能被4整除但不能被100整除。每年1、3、5、7、8、10、12为大月,2月平年有28天,闰年有29天)
代码:
def day_of_year():
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
day = int(input("请输入日期:"))
if month < 1 or month > 12:
print("月份输入错误!")
return 0
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
days_in_month[2] = 29 # 如果是闰年,将2月的天数设置为29天。
day_of_year = sum(days_in_month[:month-1]) + day
# 计算给定日期之前的天数总和,并加上给定日期的日数。这将给出给定日期是一年中的第几天
print("这是{}年的第{}天。".format(year, day_of_year))
day_of_year()
#调用函数day_of_year(),执行上述操作