python中的简单C代码---switch语句 我想在Python中写这个C++代码:< /P> 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: coutx; 开关(x) { 案例“1”: cout

python中的简单C代码---switch语句 我想在Python中写这个C++代码:< /P> 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: coutx; 开关(x) { 案例“1”: cout,python,c++,Python,C++,这是一种方法,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 opt

这是一种方法,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没有等价的
开关

你可以使用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")

你可以像这样使用字典式的结构

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'

这不会在无效输入上再次循环,它在单次传递后结束,不管是什么what@PadraicCunningham,给定的版本无论如何都是循环的。不管它是在无效的输入中。我不知道为什么对C有很多了解的人会在那里使用goto。@Padraickinningham:这个答案已经比这个问题应得的要好得多了。但是,先生,我想从用户那里获取输入:(…我更改了您的代码:def my_-dict(x):my_-dict={'1':'我的名字是阿里','2':'我的名字是哈姆扎',}如果x在my_-dict.keys()中:打印x返回my_-dict[x]其他:返回“无效输入”y=原始输入(“输入号码:”)my_-witch(y),,,,,,,,,但它显示1而不是我的名字是阿里…如果我输入数字1,你可以通过,
x=raw\u input()
。我不清楚你得到的错误。你能发布你的代码吗?是的,我用raw\u input check>>>定义my\u开关(x):my\u dict={'1':'我的名字是阿里','2':'我的名字是哈姆扎',}如果我的字典中有x():打印x返回我的字典[x]否则:返回“无效输入”y=原始输入(“输入数字:”)我的字典开关(y),,,,,,,,,如果我输入1,那么它将显示1而不显示“我的名字是阿里”,,,我想显示值删除
中的
打印
语句如果
块谢谢先生,我现在已经解决了问题>>请检查最终代码>>>定义my_开关(x):my_dict={'1':'我的名字是阿里','2':'我的名字是哈姆扎',}如果我的字典中有x():返回我的字典[x]否则:返回“无效输入”y=原始输入(“输入数字:”)打印我的字典开关(y)先生,你的技术很好…但是你的代码在输出时出错了…你能检查一下吗…并给我最后的表格…这会对我更有帮助。如果使用python 3将原始输入更改为输入,请检查错误…我已经上传了快照…>>>>我正在使用python2.7.5不是3谢谢,先生,,,,,我也解决了这个问题>>>检查最终代码>>选项={“1”:“我的名字是阿里”,“2”:“我的名字是哈姆扎”}将响应映射到键,而True:x=raw\u输入(“输入编号”)。#接受用户输入,如果选项中有x,使用python 3的
input()
。#如果选项中有键dict print options[x]#打印适当的响应中断#结束循环,否则:打印“无效输入”#否则输入无效,请再次询问