Python學習插曲之萬年曆演算法

2021-07-27 21:14:49 字數 2602 閱讀 9850

python實現萬年曆

1. 最近在學習python的過程中,想起了以前學習c語言時的萬年曆演算法,就打算寫一下,主要是為了熟悉python的語法,以此來銘記一下python的學習歷程。

2. 實現萬年曆需要用到的基本知識有

3. 以下是**實現:

#coding=utf-8  

"""@ function perpetual calendar;

@author: wly

@date: 2017-03-05

@description: 輸入乙個年份可以列印這一年的日曆。python基礎學習插曲

""""""

1.is_leap_year 判斷是否問閏年的函式

2.get_month_days 獲取乙個月有多少天

3.get_total_days 已知2023年1月1日為星期3,距某年某月多少天

4.get_start_day 獲取某年某月的第一天是星期幾

"""# 定義基礎資料

arrweek = ["sun","mon","tue","wed","thu","fri","sat"];

arrmonth = ["january","february","march","april","may","june","july","august","september","october","november","december"];

def is_leap_year(year):

if (year % 4 ==0 and year % 100 !=0 or year % 400 ==0):

return true

else:

return false

def get_month_days(year,month):

if(month in (1,3,5,7,8,10,12)):

return 31;

elif(month in (4,6,9,11)):

return 30;

elif(is_leap_year(year)):

return 29;

else:

return 28;

def get_total_days(year,month):

days = 0;

for i in range(1800,year):

if(is_leap_year(i)):

#閏年days += 366;

else:

#平年days += 365;

#一直計算到所求月份前乙個月即可

for j in range(1,month):

days += get_month_days(year, j);

return days;

def get_start_day(year,month):

#計算是星期幾

return (3 + get_total_days(year, month)) % 7;

def print_calendar(year):

for k,m in enumerate(arrmonth):

#列印日曆的月份和年份

print " ",m," ",year

print "---------------------------"

#計算這個月有幾天

day = get_month_days(year, k+1);

#計算這個月的第一天是星期幾

startday = get_start_day(year, k+1);

#列印星期表頭

for k,v in enumerate(arrweek):

print "%3s" % v,

print

#列印這個月的天數

for i in range(1,day+1):

#計算要縮排幾個單位

temp = (startday + i-1) % 7

#用於縮排格式,只要這個月的第一天縮排正確即可

if(i==1):

#迴圈列印縮排單位

for j in range(temp):

print " ",

print "%3s" % i,

#列印到星期六之後要換行

if(temp == 6) :

print

#乙個月遍歷完成列印結束分隔符

print

print "---------------------------"

#呼叫程式

print_calendar(2017);

4. 執行結果如下圖:

python製作萬年曆

最近進行python基礎培訓,課下作業製作萬年曆,之前沒做過,感覺裡面還是有很多需要學的。所謂萬年曆,就是咱們電腦或者手機的日期會記錄每個月每天對應星期幾。用python來製作萬年曆,就是從鍵盤輸入年份和月份,然後輸出對應的日曆表。在製作過程中有如下問題需要思考 判斷平年和閏年 def leap y...

簡易萬年曆

div設定 li body calendar calendar ul calendar li calendar li h2 calendar li p calendar active calendar active p calendar text calendar text h2 calendar ...

迷你萬年曆for PocketPC

1.軟體配置 軟體名稱 迷你萬年曆 軟體id ewc sys 開發平台 net compact framework 1.0 執行平台 pocketpc 2003 開發語言 vb.net 多國語言簡中 簡繁結構體系 單機版開發日期 2006 02 2006 03 最高版本 2.5註冊方法 使用者名稱 ...