switch 函数在python中怎么写
时间: 2024-05-16 08:15:02 浏览: 23
Python中没有switch语句,但可以使用字典实现类似的功能,示例如下:
```python
def switch_case(case):
switcher = {
1: "case 1",
2: "case 2",
3: "case 3"
}
return switcher.get(case, "Invalid case")
```
以上代码中,我们定义了一个函数 `switch_case`,传入一个 `case` 参数,然后使用字典 `switcher` 存储每个 case 对应的值。最后使用 `get` 方法从字典中取出对应的值,如果没有找到对应的值,则返回 "Invalid case"。使用方法如下:
```python
print(switch_case(1)) # 输出:case 1
print(switch_case(4)) # 输出:Invalid case
```
相关问题
python中switch函数用法
Python中没有内置的switch语句,但是可以使用字典来实现类似的功能。具体实现方法如下所示:
```python
def fun1():
print('This is the fun1')
def fun2():
print('This is the fun2')
def fun3():
print('This is the fun3')
def default():
print('No such fun')
switch = {
'fun1': fun1,
'fun2': fun2,
'fun3': fun3,
}
switch.get('fun1', default)()
```
在上面的代码中,我们定义了四个函数fun1、fun2、fun3和default,分别代表不同的操作。然后我们使用一个字典switch来存储这些函数,并将函数名作为字典的键。最后,我们使用get方法来获取对应的函数,并执行它。如果字典中没有对应的键,则执行默认函数default。
需要注意的是,在字典中存储函数时,不要加括号,否则会直接执行函数。另外,get方法的第二个参数是可选的,默认值为None,表示如果字典中没有对应的键,则返回None。如果需要返回其他默认值,可以将其作为第二个参数传入get方法。
python switch函数用法
在Python中,没有内置的switch/case语法。但是,我们可以使用字典来实现类似的功能。下面是一个示例代码:
```python
def fun1():
print('This is the fun1')
def fun2():
print('This is the fun2')
def fun3():
print('This is the fun3')
def default():
print('No such fun')
switch = {
'fun1': fun1,
'fun2': fun2,
'fun3': fun3,
}
switch.get('fun1', default)()
```
在上面的代码中,我们定义了几个函数fun1、fun2、fun3和default。然后,我们创建了一个字典switch,将不同的值与对应的函数关联起来。最后,我们使用get方法从字典中获取对应的函数,并执行它。如果字典中没有对应的值,则执行默认的函数。
另外,如果你想根据不同的type值执行不同的函数,可以使用类似的方法。下面是一个示例代码:
```python
def get_fun_1(s):
return s
def get_fun_2(s):
return s
def get_fun_3(s):
return s
def get_default(s):
return s
switcher = {
'a': get_fun_1,
'b': get_fun_2,
'c': get_fun_3,
}
output = switcher.get(type, get_default)(s)
```
在上面的代码中,我们定义了几个函数get_fun_1、get_fun_2、get_fun_3和get_default。然后,我们创建了一个字典switcher,将不同的type值与对应的函数关联起来。最后,我们使用get方法从字典中获取对应的函数,并执行它。如果字典中没有对应的type值,则执行默认的函数。
相关推荐
![](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)
![](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)
![](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)