利用Python函数实现万年历完整示例
本文通过Python函数封装实现万年历功能,涵盖闰年判断、月份天数计算及总天数累加逻辑。利用format()函数优化字符格式化打印,解决中文对齐问题,提供完整的交互式查询示例代码。
前言
用户可根据格式化打印字符的要求调整最终输出效果。由于中文字符排版较为复杂,建议替换为星期的英文单词以提升显示效果。format()函数支持字符串调用及独立使用,可用于格式化打印字符。
可点击格式化打印字符链接了解详细信息。
示例代码
# 判断是否闰年
def isleap(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
# 判断月的天数
def month_days(year,month):
if month in [1,3,5,7,8,10,12]:
return 31
if month == 2:
if isleap(year):
return 29
else:
return 28
return 30
# 1900年到输入年份的总天数
def total_days(year):
s = 0
for i in range(1900,year):
if isleap(i):
s += 366
else:
s += 365
return s
# 1月到输入月份的天数
def days(year,month):
s = 0
for i in range(1,month):
s += month_days(year,i)
return s
# 获取某年某月的日历
def monthcalendar(year,month):
total = total_days(year) + days(year, month)
a = total % 7
print('星期日'.center(8, ' '), end='')
print('星期一'.center(8, ' '), end='')
print('星期二'.center(8, ' '), end='')
print('星期三'.center(8, ' '), end='')
print('星期四'.center(8, ' '), end='')
print('星期五'.center(8, ' '), end='')
print('星期六'.center(8, ' '), end='')
print()
count = 0
for i in range(0, month_days(year, month) + a + 1):
if i <= a:
print(format(' ','10'), end='')
count += 1
else:
print(format(str(i - a),'^10'), end='')
count += 1
if count == 7:
count = 0
print()
print()
# 输出某年一年的日历
def yearcalendar(year):
for i in range(1,13):
print(f'{i}月:')
monthcalendar(year,i)
print()
# 开始函数
def start():
while True:
print('-------欢迎来到万历表查询页面-------')
print('1.查询某年的日历\n2.查询某年某月的日历\n3.退出查询')
print('---------------------------------')
n = int(input('请输入你的操作:'))
if n == 1:
year = int(input('请输入要查询的年份:'))
yearcalendar(year)
elif n == 2:
year = int(input('请输入要查询的年份:'))
month = int(input('请输入1-12:'))
monthcalendar(year,month)
elif n == 3:
print('退出成功')
break
else:
print('指令错误,请重新输入!!!')
if __name__ == '__main__':
start()
总结
至此,关于利用Python函数实现万年历的介绍已完成。如需了解更多Python函数实现万年历的相关内容,请搜索本站历史文章或继续浏览后续文章,感谢支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









