Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python日历程序编写

作者:整整ー世♂陰霾そ   发布日期:2026-03-26   浏览:107

# Python日历程序编写

import calendar

def show_calendar(year, month):
    # 创建一个Calendar对象
    cal = calendar.TextCalendar(calendar.SUNDAY)

    # 格式化月份为一个多行字符串,每个星期一行
    formatted_calendar = cal.formatmonth(year, month)

    # 打印格式化后的日历
    print(formatted_calendar)

if __name__ == "__main__":
    # 用户输入年份和月份
    try:
        year = int(input("请输入年份 (例如 2023): "))
        month = int(input("请输入月份 (1-12): "))

        if 1 <= month <= 12:
            show_calendar(year, month)
        else:
            print("月份必须在1到12之间")
    except ValueError:
        print("输入无效,请输入数字")

解释说明:

  1. 导入模块:我们使用Python内置的calendar模块来生成日历。
  2. 创建函数show_calendar:该函数接收年份和月份作为参数,并使用TextCalendar类生成指定年份和月份的日历。
  3. 格式化日历formatmonth方法将指定月份的日历格式化为一个多行字符串,每一行代表一个星期。
  4. 用户输入:通过input函数获取用户输入的年份和月份,并进行基本的验证。
  5. 异常处理:使用try-except块捕获用户输入的非数字字符,确保程序不会崩溃。

这个程序会根据用户输入的年份和月份显示相应的日历。

上一篇:python绝对路径怎么写

下一篇:python 数据库连接

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站