您的位置:首页 > 编程语言 > Python开发

Python 语言基础 综合训练2_编写万年历

2020-06-10 04:25 447 查看

任务要求:

1.按日历格式输出天数

2.按年月判断闰年输出正确天数

3.输出月历的正确格式

第一步:设计功能函数模块文件

cale.py

[code]#coding=utf-8

def leap_year(year):
'''
判断是否为闰年的函数
闰年的条件:
1.能被4整除,但不能被100整除的年份都是闰年
2.能被400整除的年份是闰年
不符合这两个条件的年份不是闰年
:param year: 年份
'''
if year%4==0 and year%100!=0 or year%400==0:
return True
else:
return False

def get_month_days(year,month):
'''
返回一个月的天数的函数
返回可能的天数:
1.月份为:4 6 9 11,返回30天
2.月份为:2,若为闰年,则返回29天,否则返回28天。
3.其它返回31天。
:param year: 年份
:param month: 月份
'''
days=31
if month==4 or month==6 or month==9 or month==11:
days=30
if month==2:
if leap_year(year):
days=29
else:
days=28
return days

def get_week_begin_day(year,month):
'''
获得输入年月的第一天是星期几的函数
:param year: 年份
:param month: 月份
'''
totaldays=0
for i in range(1,year):
if leap_year(i):
totaldays+=366
else:
totaldays+=365
for i in range(1,month):
totaldays +=get_month_days(year,i)
return totaldays%7+1

def get_month(year,month):
'''
输出日历格式函数
:param year: 年份
:param month: 月份
'''
t = ("日", "一", "二", "三", "四", "五", "六")
for i in t:
print(i, end="\t")
if (i=='六'):
print()
days = get_month_days(year, month)
begin_day = get_week_begin_day(year, month)

l = []
while begin_day > 0:
l.append("")
begin_day -= 1

for day in range(1, days + 1):
l.append(day)

for i in range(len(l)):
print(l[i], end="\t")
if (i + 1) % 7 == 0:
print()

'''并增加__main__判断,使得本模块脚本既可以用于导入,也可以执行。每一个模块都有一个特殊变量__name__(Python使用双下划线命名一些特殊变量),当导入这个模块时,该变量指明了模块的名字。但当该模块直接执行时,__name__变量就赋值为一个字符串“__main__”,而不再是模块名了。
'''
if __name__=='__main__':
year = int(input('请输入年份:'))
month = int(input('请输入月份:'))
get_month(year,month)

第二步:设计主调程序模块文件

main.py

[code]#coding=utf-8
import cale
year=int(input('请输入年份:'))
month=int(input('请输入月份:'))
cale.get_month(year,month)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: