Python_获取某年某月的天数

if elif else 语句、比较运算符、逻辑运算符的应用

'''
    获取一个年份,一个月份
    打印相应天数
    1 3 5 7 8 10 12  ->  31天
    2  ->  28(平年)   ->  29天(闰年)
    4 6 9 11  ->   30天
'''
# 获取一个年份
year = int(input('请输入年份:'))
# 获取一个月份
month = int(input('请输入月份:'))  
if month < 1 or month > 12:
    print('月份有误!')
elif month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
    print(str(year) + '年' + str(month) + '月有31天')
elif month == 4 or month == 6 or month == 9 or month == 11:
    print(str(year) + '年' + str(month) + '月有30天')
else:
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        print(str(year) + '年' + str(month) + '月有29天')
    else:
        print(str(year) + '年' + str(month) + '月有28天')
  • 8
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 可以使用 Python 的 calendar 模块来求某年某月天数。下面是一个例子: ```python import calendar year = 2021 month = 8 days_in_month = calendar.monthrange(year, month)[1] print(f"{year}年{month}月有{days_in_month}") ``` 输出结果为: ``` 2021年8月有31 ``` 其中,`calendar.monthrange(year, month)` 函数返回一个元组,元组的第一个元素表示该月份的第一是星期几(0 代表星期一,6 代表星期),第二个元素表示该月份的天数。因此,我们只需要取元组的第二个元素即可得到某年某月天数。 ### 回答2: 要在Python中求某年某月天数,可以使用calendar模块。首先,我们需要导入calendar模块。 然后,我们可以使用calendar模块中的monthrange函数来获取指定年份和月份的天数。monthrange函数接受两个参数,第一个参数是年份,第二个参数是月份。 以下是一个示例代码,实现了输入年份和月份后,输出该月的天数: ```python import calendar year = int(input("请输入年份:")) month = int(input("请输入月份:")) # 使用calendar模块的monthrange函数获取指定年份和月份的天数 _, days = calendar.monthrange(year, month) print(f"{year}年{month}月的天数为:{days}") ``` 在上面的代码中,我们首先使用`int(input())`函数获取输入的年份和月份,并将其转换为整数类型。然后,我们使用`calendar.monthrange(year, month)`函数获取该年份和月份的天数。 最后,我们使用f-string来输出结果。 注意:在Python中,月份的范围是1到12,而不是0到11。 希望这个回答能够帮到你! ### 回答3: 在Python中,想要求某年某月天数可以使用`calendar`模块。首先,我们需要导入`calendar`模块: ```python import calendar ``` 然后,可以使用`calendar.monthrange(year, month)`函数来获取指定年份和月份的天数,该函数返回一个元组,包含指定月份的第一的星期几和指定月份的天数。例如,我们可以这样使用: ```python year = 2022 # 指定年份 month = 9 # 指定月份 first_day, total_days = calendar.monthrange(year, month) ``` `first_day`代表指定月份的第一是星期几,以整数形式表示,星期一为0,星期二为1,以此类推。`total_days`代表指定月份的天数。 这样,我们就可以得到指定年份和月份的天数了。 接下来,我们可以输出结果: ```python print(f"{year}年{month}月有{total_days}") ``` 完整的代码如下: ```python import calendar year = 2022 # 指定年份 month = 9 # 指定月份 first_day, total_days = calendar.monthrange(year, month) print(f"{year}年{month}月有{total_days}") ``` 以上代码会输出: ``` 2022年9月有30 ``` 这样就完成了通过Python某年某月天数的操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值