简体   繁体   English

python中的简单C代码— switch语句

[英]Simple C code in python — switch statement

I want to write this C++ code in Python: 我想用Python编写以下C ++代码:

cout<<"input number";
cin>>x;
switch(x)
{
 case '1':
   cout<<"my name is ali";
 case '2':
   cout<<"my name is hamza";
 default:
   cout<<"invalid input";
}
goto again:

I also checked the dictionary statement, but maybe I am coding it incorrectly. 我也检查了字典语句,但是也许我编码不正确。

This is one way to do it, there are no switch statements in python: 这是一种实现方式,python中没有switch语句:

options = {"1":"my name is ali","2":"my name is hamza"} # map responses to keys

while True:
    x = raw_input("input number") # take user input, use `input()` for python 3
    if x in options: # if the key exists in the options dict
        print(options[x]) # print the appropriate response
        break # end the loop
    else:
        print("invalid input") # or else input is invalid, ask again

Python has no switch equivalent. Python没有等效的switch

You can use if/else 您可以使用if / else

if x == '1':
   print "my name is ali"
elif x == '2':
   print "my name is hamza"
else:
   print "invalid input"

If you are concerned that this may mean doing a lot of tests against x . 如果您担心这可能意味着对x进行了大量测试。 You can often use a dict, with the keys being values of x . 您通常可以使用dict,其键值为x eg. 例如。

x_map = {"1": "my name is ali",
         "2": "my name is hamza"}

print x_map.get(x, "invalid input")

You can use dictionary like structure like this. 您可以使用像这样的结构字典。

def my_switch(x):
    my_dict = {
            '1': 'my name is ali',
            '2': 'my name is hamza',
        }
    if x in my_dict.keys():
        return my_dict[x]
    else:
        return "invalid input"

Implementation of this function: 该功能的实现:

In [21]: my_switch('1')
Out[21]: 'my name is ali'

In [22]: my_switch('not a key')
Out[22]: 'invalid input'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM