Python 判断该月多少天不考虑闰年
时间: 2023-12-01 19:03:32 浏览: 28
可以使用 Python 的 calendar 模块来判断每个月的天数,示例代码如下:
```python
import calendar
# 输入年份和月份
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
# 输出该月的天数
days = calendar.monthrange(year, month)[1]
print("{0}年{1}月有{2}天".format(year, month, days))
```
注意,该代码不考虑闰年的影响,如果需要考虑闰年,可以使用 datetime 模块,具体实现可以参考其他文章。
相关问题
用python根据月份判断该月有多少天 不考虑闰年
可以使用 if-elif 语句根据月份判断该月有多少天,示例代码如下:
```python
month = int(input("请输入月份:"))
if month == 2:
days = 28
elif month in [4, 6, 9, 11]:
days = 30
else:
days = 31
print("该月有 %d 天" % days)
```
在代码中,首先使用 `input` 函数获取用户输入的月份,然后使用 `if-elif` 语句判断该月份有多少天,最后通过 `print` 函数将结果输出。注意,由于 `input` 函数返回的是字符串类型,因此需要使用 `int` 函数将其转换为整数类型。
用python根据月份判断该月有多少天,不考虑闰年
可以使用一个字典来实现根据月份查找天数的功能,代码如下:
```python
month_days = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
month = int(input("请输入月份:"))
days = month_days.get(month)
if days:
print("{}月有{}天".format(month, days))
else:
print("输入有误,请重新输入月份")
```
这里使用了 `get()` 方法来获取字典中对应的值,如果输入的月份不在字典中,则返回 `None`。