再战万年历

这本来是一个悲剧的故事,昨天想了很久都无法实现,仅仅判断个平闰年和月份就已经错误百出,今年参考了Snow__同学的万年历文章,总算是慢慢能够消化下来。
巨赞无比的思路,特别合适我这种小白


  • 首先判断年份是否为平闰年
  • 判断月份的天数
  • 根据平闰年和月份的天数计算某年某月距离1990有多少平闰年,某月有多少天

程序如下:

# Insure whether Year is Leap year
def is_leap_year(year):
           if(year%4 == 0 and year%100 != 0) or year % 400 == 0:
                      return True
           else:
                      return False

# Calculate how many days in the month
def get_month_day(year, month):
           days = 31
           if month == 2:
                      days = 29 if is_leap_year(year) else 28
           elif month in [4, 6, 9, 11]:
                      days = 30
           return days

# Calculate how many days before
def get_today(year, month):
           total = 0
           for i in range(1990, year):
                      if is_leap_year(year):
                                 total += 366
                      else:
                                 total += 365
           for i in range(1, month):
                      total += get_month_day(year, i)
           return total

if __name__ == '__main__':

           while True:
                      year = input('请输入年份(如:1990):')
                      month = input('请输入月份(如:1):')
                      try:
                                 year = int(year)
                                 month = int(month)
                                 if month < 1 or month > 12:
                                            print('年份或月份输入错误,请重新输入')
                                            continue
                      except:
                                 print('年份或月份输入错误,请重新输入')
                                 continue
                      break

           print('日\t一\t二\t三\t四\t五\t六')
           count = 0
           for i in range((get_today(year, month) % 7) + 1):
                      print('\t', end = '')
                      count += 1
           for i in range(1, get_month_day(year, month) + 1):
                      print(i, end = '')
                      print('\t', end = '')
                      count += 1
                      if count %7 == 0:
                                 print('\n')

很清爽的思路风格相比我自己之前的半成品而言,泥石流是什么就显而易见了。

Practice makes perfect
一起好好学习呀

你可能感兴趣的:(再战万年历)