Python中的 Switch Case(替换)
Python中 Switch Case 的替代品是什么?
与我们之前使用的所有其他编程语言不同, Python没有 switch 或 case 语句。为了绕过这个事实,我们使用字典映射。
Python3
# Function to convert number into string
# Switcher is dictionary data type here
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
# get() method of dictionary data type returns
# value of passed argument if it is present
# in dictionary otherwise second argument will
# be assigned as default value of passed argument
return switcher.get(argument, "nothing")
# Driver program
if __name__ == "__main__":
argument=0
print (numbers_to_strings(argument))
CPP
#include
using namespace std;
// Function to convert number into string
string numbers_to_strings(int argument){
switch(argument) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
default:
return "nothing";
};
};
// Driver program
int main()
{
int argument = 0;
cout << numbers_to_strings(argument);
return 0;
}
Python3
def number_to_string(agrument):
match agrument:
case 0:
return "zero"
case 1:
return "one"
case 2:
return "two"
case default:
return "something"
if __name__ = "__main__":
agrument = 0
number_to_string(agrument)
此代码类似于 C++ 中的给定代码:
CPP
#include
using namespace std;
// Function to convert number into string
string numbers_to_strings(int argument){
switch(argument) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
default:
return "nothing";
};
};
// Driver program
int main()
{
int argument = 0;
cout << numbers_to_strings(argument);
return 0;
}
输出:
Zero
但在Python 3.10 及之后, Python将支持它:
这是我的示例代码:
Python3
def number_to_string(agrument):
match agrument:
case 0:
return "zero"
case 1:
return "one"
case 2:
return "two"
case default:
return "something"
if __name__ = "__main__":
agrument = 0
number_to_string(agrument)
就像上面的所有代码一样