Python中的开关盒(替换)

Python中开关盒的替换是什么?

null

与我们以前使用的所有其他编程语言不同,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))


此代码类似于C++中的给定代码:

CPP

#include<bits/stdc++.h>
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"
if __name__ = "__main__" :
agrument = 0
number_to_string(agrument)


就像上面所有的代码一样

本文由 沙申克·米什拉(古卢) .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享