python打印日歷
阿新 • • 發佈:2017-12-05
字符 字符串 image ges november 一個 nbsp 圖片 end
#未優化的代碼
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 in month_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 = 0 26 #主體 27 for index in range(1,43): 28 29 ifindex < 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 return False 37 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 def get_start_day(year,month,date): 55 total_days = 0 56 #遍歷年份 57 for one_year in range(2010,year): 58 if is_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 += date 69 70 #求輸入的年月日是星期幾 71 day = (total_days % 7 + 5 - 1) % 7 72 73 #print(total_days) 74 #print(day) 75 return day 76 77 #輸入一個年份和月份,輸出這月有多少天 78 #1,3,5,7,8,10,12--------31天 79 #4,6,9,11 --------------30天 80 #如果是閏年2------------29天 81 #不是閏年 2-------------28天 82 def days_of_month(year,month): 83 days = 0 84 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 elif is_leap_year(year): 89 days = 29 90 else: 91 days = 28 92 return days 93 94 def is_leap_year(year): 95 if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: 96 return True 97 return False 98 99 def main(): 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()
python打印日歷