簡體   English   中英

python中的簡單C代碼— switch語句

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM