获取用户输入月份,输出该月有多少天(考虑闰年)的python代码
时间: 2023-10-26 09:15:42 浏览: 50
以下是Python代码,可以获取用户输入的月份并输出该月有多少天,考虑了闰年的情况。
```python
year = input("请输入年份:\n")
month = input("请输入月份:\n")
year = int(year)
month = int(month)
# 判断该月份的天数
if month in [1, 3, 5, 7, 8, 10, 12]:
print("{}年{}月有31天。".format(year, month))
elif month in [4, 6, 9, 11]:
print("{}年{}月有30天。".format(year, month))
elif month == 2:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("{}年2月有29天。".format(year))
else:
print("{}年2月有28天。".format(year))
else:
print("输入错误,请重新输入。")
```
这段代码首先要求用户输入年份和月份,然后根据月份的不同,判断该月份有多少天。当月份为1、3、5、7、8、10、12时,有31天;当月份为4、6、9、11时,有30天;当月份为2时,需要判断年份是否为闰年。若为闰年,则有29天;否则为28天。
相关问题
python获取用户输入月份,输出该月有多少天(考虑闰年)
可以使用Python中的datetime模块来获取月份的天数,代码如下:
```python
import datetime
month = int(input("请输入月份:"))
year = datetime.datetime.now().year
if month == 2:
if year % 4 == and year % 100 != or year % 400 == :
print("该月有29天")
else:
print("该月有28天")
elif month in [1, 3, 5, 7, 8, 10, 12]:
print("该月有31天")
else:
print("该月有30天")
```
首先,使用input函数获取用户输入的月份,然后使用datetime模块获取当前年份。接着,根据月份判断该月有多少天,其中2月需要考虑闰年的情况。如果当前年份是闰年,则2月有29天,否则有28天。其他月份根据常识判断即可。最后,使用print函数输出结果。
python获取用户输入月份,输出该月有多少天(考虑闰年)。
以下是Python代码,用于获取用户输入月份并输出该月有多少天(考虑闰年):
```python
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
# 判断是否为闰年
is_leap_year = False
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
is_leap_year = True
# 判断每个月的天数
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
elif month in [4, 6, 9, 11]:
days = 30
else:
if is_leap_year:
days = 29
else:
days = 28
print("{0}年{1}月有{2}天".format(year, month, days))
```
在代码中,首先通过 `input` 函数获取用户输入的年份和月份,并将其转换为整数。然后,判断该年份是否为闰年,如果是,则将 `is_leap_year` 标记设置为 `True`。接着,根据月份判断该月的天数,如果是大月份(1、3、5、7、8、10、12),则天数为 31 天;如果是小月份(4、6、9、11),则天数为 30 天;如果是二月份,则根据是否闰年来判断天数。最后,使用 `print` 函数输出结果。
注意:在Python 2.x版本中,应该使用 `raw_input` 函数代替 `input` 函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)