[英]Simple C code in python — switch statement
我想用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:
我也检查了字典语句,但是也许我编码不正确。
这是一种实现方式,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没有等效的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")
您可以使用像这样的结构字典。
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.