题目:输入某年某月某日,判断这一天是这一年的第几天?
方法一:
# 判断是否是闰年
def isLeapYear(year):
# 1、能整除4且不能整除100 2、能整除400
if((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):
# 如果是闰年,返回True
return True
# 平年,返回False
return False
# 根据输入的月份,返回该月前的几个月的总天数
def _month(year, month):
if(isLeapYear(year)):
# 闰年天数
months = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366)
else:
# 平年天数
months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365)
if 0 < month <= 12:
# 该月前的几个月的总天数
sum = months[month - 1]
# 返回总天数
return sum
# 计算这一天是这一年的第几天
def _day(year, month, day):
# 返回这一天是这一年的第几天
return day + _month(year, month)
# 打印总天数
def func():
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
day = int(input("请输入天数:"))
print(_day(year, month, day))
if __name__ == "__main__":
func()
方法二:使用switch-case语句:
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
# 判断是否是闰年
def isLeapYear(year):
# 1、能整除4且不能整除100 2、能整除400
if ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):
# 如果是闰年,返回True
return True
# 平年,返回False
return False
# 在此方法中使用switch-case
def countDay(year, month, day):
for case in switch(month):
if case(1):
sum = 0
break
if case(2):
sum = 31
break
if case(3):
sum = 59
break
if case(4):
sum = 90
break
if case(5):
sum = 120
break
if case(6):
sum = 121
break
if case(7):
sum = 181
break
if case(8):
sum = 212
break
if case(9):
sum = 243
break
if case(10):
sum = 273
break
if case(11):
sum = 304
break
if case(12):
sum = 334
break
# 如果是闰年,在天数上加1
if(isLeapYear(year)):
sum += 1
# 否则计算这一天在这一年中是第几天
sum += day
return sum
def func():
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
day = int(input("请输入天数:"))
print(countDay(year, month, day))
if __name__ == "__main__":
func()