2016-08-02 86 views
0

如果我正在制作一个能够翻译单词的程序,有没有一种方法可以不使用elif每个齿,只需要编写单词来翻译。这就是我现在得到的!如何减少elif语句的使用?

print("English to Exrian Dictionary") 

search = input("Enter the word you would like to translate: ").lower() 

if search == "ant": 
    print("Ulf") 
elif search == "back": 
    print("Zuwp") 
elif search == "ban": 
    print("Zul") 
elif search == "bat": 
    print("Zuf") 
elif search == "bye": 
    print("Zio") 
elif search == "wumohu": 
    print("Camera") 
elif search == "car": 
    print("Wuh") 
elif search == "carrot": 
    print("Wuhhef") 
elif search == "cat": 
    print("Wuf") 
elif search == "doctor": 
    print("vewfeh") 
elif search == "dog": 
    print("Ves") 
elif search == "duck": 
    print("Vawp") 
elif search == "egg": 
    print("Oss") 
elif search == "enter": 
    print("Olfoh") 
elif search == "experiment": 
    print("Oxkohymolf") 
elif search == "fat": 
    print("Tuf") 
elif search == "flower": 
    print("Tnecoh") 
elif search == "goal": 
    print("Seun") 
elif search == "goat": 
    print("Seuf") 
elif search == "hand": 
    print("Rulv") 
elif search == "hat": 
    print("Ruf") 
elif search == "hello": 
    print("Ronne") 
elif search == "hello": 
    print("Ronne") 
elif search == "house": 
    print("Reago") 
elif search == "hello": 
    print("Ronne") 
elif search == "information": 
    print("Yltehmufyel") 
elif search == "inspiration": 
    print("Ylgkyhufyel") 
elif search == "lawyer": 
    print("Nucioh") 
elif search == "no": 
    print("Le") 
elif search == "yes": 
    print("Iog") 
else: 
    print("No results were found for '" + search + "'") 
+0

请不要发布的代码图像。请改为在问题中输入您的代码。 – bernie

+2

A ['dict'](https://docs.python.org/3/library/stdtypes.html#typesmapping)似乎是合适的。 – jedwards

+0

使用映射。检查映射中是否存在“搜索”并打印其值,否则*未找到结果... * –

回答

0

您可以只使用一个dict对象。

例子:

words = {'ant': 'Ulf', 'back': 'Zuwp', 'ban' : 'Zul'} # etc 
try: 
    print(words[search]) 
except KeyError as e: 
    print("No results were found for '" + search + "'") 
2

使用dict将每个输入映射到适当的输出。

print("English to Exrian Dictionary") 
d = {"ant": "Ulf", 
    "back": "Zuwp", 
    # etc 
    } 

search = input("Enter the word you would like to translate: ").lower() 

if search in d: 
    print(d[search]) 
else: 
    print("No results were found for '" + search + "'") 
0

这可能帮助:

def translate(item): 
try: 
    return { 
     'ant': "Ulf", 
     'back': "Zuwp", 
     'ban': "Zul" 
    }[item] 
except KeyError as e: 
    return "No results were found for '" + search + "'" 

print("English to Exrian Dictionary") 

search = raw_input("Enter the word you would like to translate: ").lower() 

print translate(search)