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

时间:2014-08-09 10:14:15

标签: python c++

我想用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:

我还检查了字典语句,但也许我编写错误。

3 个答案:

答案 0 :(得分:1)

这是一种方法,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

答案 1 :(得分:0)

Python没有等效的switch

您可以使用if / else

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

如果您担心这可能意味着针对x进行了大量测试。您经常可以使用dict,其键值为x。例如

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

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

答案 2 :(得分:0)

您可以像这样使用字典结构。

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"

此功能的实施:

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

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