获取用户输入月份,输出该月有多少天(不考虑闰年)。Python
时间: 2024-09-28 21:07:34 浏览: 50
在Python中,你可以创建一个函数来获取用户的输入月份,然后根据常见的每个月的天数来判断并输出结果。下面是一个简单的示例:
```python
def days_in_month():
month = int(input("请输入月份(1-12):")) # 获取用户输入的月份
if month < 1 or month > 12: # 检查是否在有效范围内
print("输入错误,月份应为1-12")
else:
# 定义一个字典存储每个月的天数
days_in_month_dict = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
if month == 2 and is_leap_year(): # 如果是2月,需要检查是否为闰年
print(f"二月有{days_in_month_dict[month]}天")
else:
print(f"{month}月有{days_in_month_dict[month]}天")
# 辅助函数检查是否为闰年
def is_leap_year():
year = int(input("请输入年份(默认当前年份):"))
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
days_in_month()
```
在这个例子中,我们假设用户会输入一个整数表示月份,然后根据这个值直接从字典`days_in_month_dict`中获取天数。对于2月,我们还额外询问用户是否想检查是否为闰年。
阅读全文