python case使用例子
时间: 2024-04-22 19:19:52 浏览: 160
当谈到Python中的case使用例子时,通常是指使用`switch`语句来实现多分支条件判断。然而,Python并没有内置的`switch`语句,但我们可以使用其他方式来实现类似的功能。以下是一些常见的Python中case使用例子:
1. 使用if-elif-else语句:
```python
def get_day_of_week(day):
if day == 1:
return "Monday"
elif day == 2:
return "Tuesday"
elif day == 3:
return "Wednesday"
elif day == 4:
return "Thursday"
elif day == 5:
return "Friday"
elif day == 6:
return "Saturday"
elif day == 7:
return "Sunday"
else:
return "Invalid day"
print(get_day_of_week(3)) # 输出: Wednesday
```
2. 使用字典映射:
```python
def get_day_of_week(day):
days = {
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
7: "Sunday"
}
return days.get(day, "Invalid day")
print(get_day_of_week(3)) # 输出: Wednesday
```
3. 使用函数映射:
```python
def monday():
return "Monday"
def tuesday():
return "Tuesday"
def wednesday():
return "Wednesday"
def thursday():
return "Thursday"
def friday():
return "Friday"
def saturday():
return "Saturday"
def sunday():
return "Sunday"
def get_day_of_week(day):
switcher = {
1: monday,
2: tuesday,
3: wednesday,
4: thursday,
5: friday,
6: saturday,
7: sunday
}
func = switcher.get(day, lambda: "Invalid day")
return func()
print(get_day_of_week(3)) # 输出: Wednesday
```
这些例子展示了在Python中实现类似`switch`语句的不同方法。根据具体的需求,你可以选择适合的方式来实现多分支条件判断。
阅读全文