利用Python如何输出某一年的日历?

利用自定而下的思想,将问题进行一步一步的分解,最后可解决问题

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值