zhou11119 2023-11-27 19:02 采纳率: 83.7%
浏览 6

python问题求月历

img

a,b=map(int,input().split())
if (a % 4 == 0 and a % 100 != 0) or a % 400 == 0 and a==2:
    print('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')
else:
    print('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')
elif b==1:
    print('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')
elif b==3:
    print('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')
elif b==4:
    print('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')
elif b==5:
    print('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')
elif b==6:
    print('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')
elif b==7:
    print('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')
elif b==8:
    print('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')
elif b==9:
    print('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')
elif b==10:
    print('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')
elif b==11:
    print('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')
elif b==12:
    print('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')

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-11-27 21:31
    关注

    【以下回答由 GPT 生成】

    首先,建议您使用calendar模块来生成月历,而不是手动编写条件语句。calendar模块提供了一些方法来生成年、月、周等日历信息。

    以下是优化后的代码:

    import calendar
    
    year, month = map(int, input().split())
    
    cal = calendar.monthcalendar(year, month)
    for week in cal:
        print(' '.join(str(day) for day in week))
    

    在优化后的代码中,我们使用calendar.monthcalendar(year, month)来获取指定年份、月份的日历信息。此方法返回一个二维列表,表示了指定月份的每一周。

    然后,我们使用一个循环遍历每一周,并使用' '.join()方法来将周内的日期转换为字符串并以空格分隔,最后打印出来。

    这样,优化后的代码更具可读性和简洁性,并且不需要手动处理闰年的情况。

    如果您只想打印出月份中的数字,并且不需要打印空白的日期,可以稍微修改一下代码,如下所示:

    import calendar
    
    # 输入年份和月份
    year, month = map(int, input().split())
    
    # 获取指定月份的日历信息
    cal = calendar.monthcalendar(year, month)
    
    # 打印月份中的数字,以空格分隔
    for week in cal:
        print(' '.join(str(day) for day in week if day != 0))
    

    这样修改后,如果某一天为0,即表示它不是指定月份的日期,我们就不打印出来。这样可以使输出更加整洁。



    【相关推荐】



    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

问题事件

  • 创建了问题 11月27日

悬赏问题

  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络
  • ¥66 关于川崎机器人调速问题
  • ¥15 winFrom界面无法打开
  • ¥30 crossover21 ARM64版本安装软件问题
  • ¥15 mymetaobjecthandler没有进入
  • ¥15 mmo能不能做客户端怪物