在Python中编写一个程序来判断当前的季节,可以使用以下几种方法:
方法一:使用if-elif-else语句
```python
def get_season(month):
if month == 1 or month == 2 or month == 12:
return "冬季"
elif month >= 3 and month <= 5:
return "春季"
elif month >= 6 and month <= 8:
return "夏季"
elif month >= 9 and month <= 11:
return "秋季"
else:
return "输入不合法"
获取当前月份
current_month = int(input("请输入当前月份(1-12):"))
print("当前季节是:", get_season(current_month))
```
方法二:使用字典映射
```python
seasons = {
1: "冬季",
2: "冬季",
3: "春季",
4: "春季",
5: "春季",
6: "夏季",
7: "夏季",
8: "夏季",
9: "秋季",
10: "秋季",
11: "秋季",
12: "冬季"
}
获取当前月份
current_month = int(input("请输入当前月份(1-12):"))
print("当前季节是:", seasons[current_month])
```
方法三:使用列表和条件判断
```python
def get_season(month):
season_ranges = [
(12, 1, 2), 冬季
(3, 4, 5), 春季
(6, 7, 8), 夏季
(9, 10, 11) 秋季
]
for start, end, season in season_ranges:
if month >= start and month <= end:
return season
return "输入不合法"
获取当前月份
current_month = int(input("请输入当前月份(1-12):"))
print("当前季节是:", get_season(current_month))
```
以上三种方法都可以实现根据输入的月份判断当前季节的功能。你可以根据自己的需求和喜好选择合适的方法。