利用自定而下的思想,将问题进行一步一步的分解,最后可解决问题
def getYear():
print("This program prints the calendar of a given year.")
year = int(input("Please enter a year(after 1900: )"))
return year
def firstDay(year):
"""
返回第一天是哪一天 0-> 星期1
"""
k = leapYears(year)
n = (year-1900)*365 +k
return (n+1) %7
def leapYears(year):
"""
判断从1900 到year中间有多少个闰年
"""
count = 0
for y in range(1900, year):
if y%4==0 and (y%400==0 or y%100!=0):
count += 1
return count
def printCalendar(year, w):
print()
print("============" + str(year) + "============")
first = w
for month in range(12):
heading(month)
first = oneMonth(year, month, first)
def heading(month):
"""
输出提示,表示这是第几月
"""
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]
print(" %s "%(months[month]))
print(" Mon Tue Wed Thu Fri Sat Sun")
def oneMonth(year, month, first):
"""
"""
d = days(year, month)
frame = layout(first,d)
printMonth(frame)
return (first+d)%7
def days(y,m):
"""
返回第几个月有多少天
"""
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
d = month_days[m]
if(m==1) and (y%4==0 and(y%400==0 or y%100!=0)):
# 闰年的2月
d += 1
return d
def layout(first, d):
frame = 42* [""] # 表示的是整个的框架6 * 7
if first == 0:
first = 7
j = first-1
for i in range(1, d+1):
frame[j]=i
j = j+1
return frame
def printMonth(frame):
for i in range(42):
print("%4s"%(frame[i]), end='')
if (i+1)%7==0:
print()
def main():
# year = getYear()
w = firstDay(2012)
printCalendar(2012, w)
main()