如何减少elif语句的使用?

时间:2016-08-02 00:35:56

标签: python

如果我正在制作一个合法的程序来翻译单词,那么有没有办法不使用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 + "'")

3 个答案:

答案 0 :(得分: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 + "'")

答案 1 :(得分: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)

答案 2 :(得分: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 + "'")