python万年历实验报告_Python实现的简单万年历例子分享

#!/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):

"""

获取199

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实验名称:Python万年历 实验目的:使用Python编写一个可以输出任意年份和月份的日历的程序,并学习Python的基本语法和日期时间模块的使用。 实验步骤: 1. 导入模块 在Python中要使用日期时间模块,需要先导入模块。在程序的开头使用以下代码导入日期时间模块。 ```python import datetime ``` 2. 输入年份和月份 使用`input()`函数让用户输入要查询的年份和月份。 ```python year = int(input("请输入要查询的年份:")) month = int(input("请输入要查询的月份:")) ``` 3. 获取当月第一天的星期几 使用`datetime.date()`函数获取当月第一天的日期,再使用`.weekday()`函数获取星期几。 ```python first_day = datetime.date(year, month, 1) weekday = first_day.weekday() ``` 4. 计算当月天数 使用`datetime.timedelta()`函数计算当月的天数。 ```python if month == 12: days = (datetime.date(year+1, 1, 1) - datetime.timedelta(days=1)).day else: days = (datetime.date(year, month+1, 1) - datetime.timedelta(days=1)).day ``` 5. 输出日历 使用循环输出当月的日历。 ```python print("日 一 二 三 四 五 六") for i in range(weekday): print(" ", end="") for i in range(1, days+1): if i < 10: print("", end=" ") print(i, end=" ") if (i+weekday) % 7 == 0 or i == days: print("") ``` 6. 完整代码 ```python import datetime year = int(input("请输入要查询的年份:")) month = int(input("请输入要查询的月份:")) first_day = datetime.date(year, month, 1) weekday = first_day.weekday() if month == 12: days = (datetime.date(year+1, 1, 1) - datetime.timedelta(days=1)).day else: days = (datetime.date(year, month+1, 1) - datetime.timedelta(days=1)).day print("日 一 二 三 四 五 六") for i in range(weekday): print(" ", end="") for i in range(1, days+1): if i < 10: print("", end=" ") print(i, end=" ") if (i+weekday) % 7 == 0 or i == days: print("") ``` 实验结果: 输入年份和月份,程序会输出该月的完整日历,例如输入2022年3月,输出结果如下: ``` 请输入要查询的年份:2022 请输入要查询的月份:3 日 一 二 三 四 五 六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ``` 实验总结: 通过这个实验,我学习了Python的基本语法和日期时间模块的使用,并且实现了一个实用的小程序。在编写代码的过程中,我也遇到了一些问题,例如计算当月天数时需要考虑闰年的情况,但是通过查找资料和思考,我最终解决了这些问题。这个实验让我更加深入地了解了Python语言,也为我今后的编程学习打下了基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值