创建一个程序来询问用户外语词汇

时间:2019-05-05 17:54:02

标签: python python-3.x

我需要编写一个程序来询问用户外语翻译。基本上,该程序提供一个单词,用户将键入所提供的西班牙语单词的英文单词。每当有一个正确的答案时,程序都会给出肯定的回答。对于每个错误,给出正确答案。该程序还需要保持分数并在最后报告正确答案的数量。

english_list = ["fire","apple","morning","river","wind"]
spanish_list = ["fuego","manzana","mañana","río","viento"]
english_to_spanish = dict(zip(english_list, spanish_list))
spanish_to_english = dict(zip(spanish_list, english_list))

def translate(word):
    translation = english_to_spanish.get(word)
    if translation:
        return translation

    translation = spanish_to_english.get(word)
    if translation:
        return translation

    raise Exception('Word {0} does not exists'.format(word))

print("Welcome to the English <--> Spanish Quiz")

该代码应在整个西班牙语词典中对用户进行测验。我对如何以测验格式设置代码感到困惑,以便用户可以与之有效地交互。我应该使用作为pythons字典一部分的外来词。仅使用Python词典访问这些外来词,如何编写类似的代码。

1 个答案:

答案 0 :(得分:0)

print('Type each translation, or just hit ENTER to exit.')

for sp, en in spanish_to_english.items():
    response = input(sp + '? ')
    if response == '':
        break  # empty response -> end of quiz
    print(response == en)
    print('')

将显示response == en布尔表达式 为TrueFalse

如果需要,可以选择显示正确答案:

    print(response == en)
    if response != en:
        print('The correct answer is:', en)