在Python中打印输出日历的多种方法(python用for打印全年日历)

如何在 Python 中打印日历?Python提供了一个内置的函数来打印日历,它还允许基于日历执行许多操作,有很多方法可以打印日历。让我们看看如何打印python日历。

在Python中打印输出日历的多种方法(python用for打印全年日历)

如何在Python中使用calendar

Python提供了一个内置模块calendar来打印输出日历,并允许执行其他各种操作。calendar模块有许多类和函数,可用于打印理想化的日历。日历从星期一开始,到星期日结束。在下面的代码中,我们使用 calendar.month()函数打印一个特定的月份,该函数有两个参数年份和月份。

在Python中打印输出日历的多种方法(python用for打印全年日历)

输出:

在Python中打印输出日历的多种方法(python用for打印全年日历)

不使用calendar模块打印输出日历

在不使用calendar模块的情况下打印日历可能是一件复杂的事情,通过使用循环、if-else判断、数学计算来实现。

在Python中打印输出日历的多种方法(python用for打印全年日历)

在Python中打印全年日历

我们使用calendar模块在python中打印全年日历,calendar.calendar()函数,以年份为参数。

在Python中打印输出日历的多种方法(python用for打印全年日历)

输出:

在Python中打印输出日历的多种方法(python用for打印全年日历)

calendar模块其他用法

使用calendar.isleap()判断闰年使用calendar.leapdays()返回在两个年份之间的闰年总数。使用calendar.monthrange()返回一个元组数据(两个整数)。第一个:代表本月起始星期数(0:星期一… 6:星期天)第二个:代表本月最后一天的日期数,即该月天数使用calendar.monthlen()返回指定月的天数。

在Python中打印输出日历的多种方法(python用for打印全年日历)

文中涉及代码:

import calendary=2023m=3print(calendar.month(y,m))month ={1:January,2:February,3:March,4:April,5:May,6:June,7:July,8:August,9:September,10:October,11:November,12:December}day =(y-1)%400day =(day//100)*5+ ((day %100)- (day %100)//4)+ ((day %100)//4)*2day = day %7nly=[31,28,31,30,31,30,31,31,30,31,30,31]ly =[31,29,31,30,31,30,31,31,30,31,30,31]s=if y %4==:for i inrange(m-1): s+= ly[i]else:for i inrange(m-1): s+= nly[i]day+=s%7day=day%7space=space=space.rjust(2,)print(Su,Mo,Tu,We,Th,Fr,Sa)if m==9 or m==4 or m==6 or m==11:for i inrange(31+day):if i<=day:print(space, end=)else:print(“{:02d}”.format(i-day), end=)if(i+1)%7==:print()elif m==2:if y%4==: p=30else: p=29for i inrange(p+day):if i<=day:print(space, end=)else:print(“{:02d}”.format(i-day), end =)if(i+1)%7==:print()else:for i inrange(32+day):if i<=day:print(space, end=)else:print(“{:02d}”.format(i-day), end=)if(i+1)%7==:print()print()print(calendar.calendar(2023))print(calendar.isleap(2022))# Falseprint(calendar.leapdays(2000,2023))# 6print(calendar.monthrange(2023,3))# (2,31)print(calendar.monthlen(2023,3))# 31

感谢阅读,关注我,精彩继续。

免责声明:文章内容来自互联网,本站仅提供信息存储空间服务,真实性请自行鉴别,本站不承担任何责任,如有侵权等情况,请与本站联系删除。
转载请注明出处:在Python中打印输出日历的多种方法(python用for打印全年日历) https://www.bxbdf.com/a/31691.shtml

上一篇 2023-05-07 13:28:54
下一篇 2023-05-07 13:30:33

猜你喜欢

联系我们

在线咨询: QQ交谈

邮件:362039258#qq.com(把#换成@)

工作时间:周一至周五,10:30-16:30,节假日休息。