python万年历实现代码_python如何实现万年历效果

#coding:utf-8

defleap_year(year):#判断平瑞年

ifyear%4==0andyear%100!=0oryear%400==0:

returnTrue

else:

returnFalse

defgetMonthDays(year,month):#得到每个年份每月的天数

days=31

ifmonth==2:

ifleap_year(year):

days=29

else:

days=28

elifmonth==4ormonth==6ormonth==9ormonth==11:

days=30

returndays

defgetTotalDays(year,month):#计算星期

totalDays=0

foriinrange(1,year):

ifleap_year(i):

totalDays+=366

else:

totalDays+=365

foriinrange(1,month):

totalDays+=getMonthDays(year,i)

returntotalDays

year=input("输入年份:")

month=input("请输入月:")

iCount=0

print"日\t一\t二\t三\t四\t五\t六"

i=1

foriinrange((getTotalDays(year,month)%7)+1):

print'\t',

iCount+=1

foriinrange(1,getMonthDays(year,month)+1):

printi,'\t',

iCount+=1

ifiCount%7==0:

print''

下面是一个简易的 Python 万年历实现步骤以及代码: 步骤: 1. 导入需要的模块,比如 `calendar` 和 `datetime`。 2. 定义一个函数,用于获取指定年份和月份的日历信息。在该函数中,先使用 `calendar.monthrange()` 方法获取指定年份月份的天数和第一天是星期几,然后使用 `calendar.monthcalendar()` 方法获取指定年份月份的日历数据。 3. 定义一个函数,用于将获取到的日历数据进行格式化输出。在该函数中,遍历日历数据,将每个日期对应的空格和数字组合成一个字符串,最后按照一定的格式输出即可。 4. 在主函数中,读取用户输入的年份和月份,调用上述函数获取并输出指定年份和月份的万年历代码: ```python import calendar import datetime def get_calendar(year, month): # 获取该月第一天是星期几和该月的天数 first_day_weekday, month_days = calendar.monthrange(year, month) # 获取该月的日历数据 month_calendar = calendar.monthcalendar(year, month) # 格式化输出日历数据 print(f"{' '*20}{calendar.month_name[month]} {year}") print(" Mo Tu We Th Fr Sa Su") for week in month_calendar: week_str = "" for day in week: if day == 0: week_str += " " else: week_str += f"{day:2d} " print(week_str) if __name__ == "__main__": year = int(input("请输入年份:")) month = int(input("请输入月份:")) get_calendar(year, month) ``` 运行程序后,输入年份和月份,即可输出指定年份和月份的万年历
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值