Home >Backend Development >Python Tutorial >Python实现的简单万年历例子分享

Python实现的简单万年历例子分享

WBOY
WBOYOriginal
2016-06-16 08:44:272761browse

复制代码 代码如下:
#!/usr/bin/env python2
#-*- coding:utf-8 -*-
__author__ = 'jalright'

"""
使用python实现万年历
"""

def is_leap_year(year):
    """
判断是否是闰年,返回boolean值
    """
    if year/4==0 and  year/400 !=0:
        return True
    elif year/100 == 0 and year/400 ==0 :
        return True
    else:
        return False

def getMonthDays(year,month):
    """
获取指定年月的月份有多少天
    """
    days = 31        #31天居多,设置为默认值
    if month == 2 :    #2月份要判断是否是闰年
        if is_leap_year(year):
            days=29
        else:
            days=28;
    elif month in [4,6,9,11]:     #判断小月,只有30天
        days=30
    return days

def getTotalDays(year,month):
    """
获取1990-01-01离现在有多少天,1990-01-01是星期一,以这个为标准来判断星期
    """
    totalDays=0
    for i in range(1990,year):     #使用range来循环,算出多少年多少天
        if is_leap_year(i):        #判断是否是闰年
            totalDays += 366
        else:
            totalDays += 365
    for i in range(1,month):       #使用range循环,算出今年前面几个月过了多少天
        totalDays +=getMonthDays(year,i)
    return totalDays


if __name__ == '__main__':
    while True:                                 #循环判断是否输入错误的格式
        print "××××××××××python实现万年历××××××××"
        year = raw_input("请输入年份(如:1990):")
        month = raw_input("请输入月份:如:1")
        try:                                    #捕捉输入异常格式和月份的正确
            year = int(year)
            month = int(month)
            if month 1:            #判断月份是否输入错误,错误就重新开始循环
                print "年份或者月份输入错误,请重新输入!"
                continue
        except:                                 #捕捉到转换成整型异常,输出提示,重新开始循环
            print "年份或者月份输入错误,请重新输入!"   
            continue
        break     #如果没有异常就跳出循环
    #if is_leap_year(year):
    #    print "%s是润年"%year
    #else:
    #    print "%s是平年"%year
    #print "%s月份总共有%s天!"%(month,getMonthDays(year,month))

    print "日\t一\t二\t三\t四\t五\t六"
    iCount = 0      #计数器来判断是否换行
    for i in range(getTotalDays(year,month)%7):
        print '\t',                 #输出空不换行
        iCount+=1
    for i in range(1,getMonthDays(year,month)):
        print i,
        print '\t',
        iCount +=1
        if iCount%7 == 0 :           #计数器取余为0,换行
            print ''

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn