#未優化的代碼
1 #輸出月曆
2 def print_calendar(year,month,date = 1):3 month_dict = {'1':'January','2':'February','3':'March','4':'April','5':'May','6':'June','7':'July',4 '8':'August','9':'September','10':'October','11':'November','12':'December'}5
6 #數字月份轉換為字元串,并判斷月份和号數是否合法
7 if month in range(1,13) and date in range(1,31):8 month_str =str(month)9 if month_str inmonth_dict:10 month_str =month_dict[month_str]11 else:12 print('月份或号數輸入不合法')13 return -1
14
15 #頭部
16 print('%15s%8d'%(month_str,year))17 print('-'*33)18 print('Sun Mon Tue Wed Thu Fri Sat')19
20 #得到每月1号是星期幾
21 first_day = get_start_day(year,month,1)22 #得到此月有多少天
23 month_num =days_of_month(year,month)24
25 each_day =026 #主體
27 for index in range(1,43):28
29 if index < first_day + 1:30 print(' '*5,end = '')31 else:32 if (index - 1) % 7 ==0:33 print('')34 each_day += 1
35 if each_day >month_num:36 returnFalse37 if each_day < 10:38 if each_day ==date:39 print('%-5s'%('--'),end = '')40 else:41 print('%-4d'%(each_day),end = '')42 else:43 if each_day ==date:44 print('%-5s'%('--'),end = '')45 else:46 print('%-5d'%(each_day),end = '')47
48
49 #輸入一個年月日,判斷是星期幾
50 #需要一個比較标準:2010-1-1是星期五
51 #計算目前距離标準過了多少天(total_days % 7 + 5 -1)%7
52 #先周遊年份,是閏年+366,不是+365
53 #再周遊月份,31,30,29,28
54 defget_start_day(year,month,date):55 total_days =056 #周遊年份
57 for one_year in range(2010,year):58 ifis_leap_year(one_year):59 total_days += 366
60 else:61 total_days += 365
62 #print(total_days)
63 #周遊月份
64 for one_month in range(1,month):65 total_days +=days_of_month(year,one_month)66 #print(total_days)
67 #加上當月号數,則求得總共過了多少天
68 total_days +=date69
70 #求輸入的年月日是星期幾
71 day = (total_days % 7 + 5 - 1) % 7
72
73 #print(total_days)
74 #print(day)
75 returnday76
77 #輸入一個年份和月份,輸出這月有多少天
78 #1,3,5,7,8,10,12--------31天
79 #4,6,9,11 --------------30天
80 #如果是閏年2------------29天
81 #不是閏年 2-------------28天
82 defdays_of_month(year,month):83 days =084 if month in (1,3,5,7,8,10,12):85 days = 31
86 elif month in (4,6,9,11):87 days = 30
88 elifis_leap_year(year):89 days = 29
90 else:91 days = 28
92 returndays93
94 defis_leap_year(year):95 if year % 4 == 0 and year % 100 != 0 or year % 400 ==0:96 returnTrue97 returnFalse98
99 defmain():100 print('*'*33)101 year = int(input('請輸入年份:'))102 month = int(input('請輸入月份:'))103 date = int(input('請輸入号數:'))104 print('*'*33)105 #某年某月有多少天
106 #days = days_of_month(year,month)
107 #print('{}年{}月有{}天'.format(year,month,days))
108 #某年某月某日是星期幾
109 #day = get_start_day(year,month,date)
110 #print('{}年{}月{}日是星期{}'.format(year,month,date,day))
111 #列印月曆
112 print_calendar(year,month,date)113
114 #執行
115 main()