python有switch语句吗
时间: 2023-05-26 17:03:24 浏览: 113
Python 没有内置的 switch 语句,但可以使用 if-elif-else 系列语句来实现类似的功能。另外,还可以使用字典和函数操作来模仿 switch。如下所示:
1. if-elif-else 语句:
```
x = 5
if x == 1:
print("number is 1")
elif x == 2:
print("number is 2")
elif x == 3:
print("number is 3")
else:
print("number is not between 1 and 3")
```
2. 字典:
```
def one():
print("number is 1")
def two():
print("number is 2")
def three():
print("number is 3")
switcher = {
1: one,
2: two,
3: three
}
switcher.get(x, lambda:print("number is not between 1 and 3"))()
```
3. 函数操作:
```
def one():
print("number is 1")
def two():
print("number is 2")
def three():
print("number is 3")
def switch(x):
dictionary = {
1:one,
2:two,
3:three
}
dictionary.get(x, lambda:print("number is not between 1 and 3"))()
switch(1) #number is 1
switch(4) #number is not between 1 and 3
```
阅读全文