创建“Flashcard”词汇表程序

时间:2017-06-30 17:42:36

标签: python python-3.x dictionary

我想在Python 3中创建一个基本上是词汇抽认卡的程序。我可以列出术语,添加术语或显示随机定义以尝试并准确猜测。一旦猜到准确,我就可以选择另一种定义进行猜测。或者,我希望能够显示随机键:值对,并继续查看对,直到我输入EXIT

我已经使用字典制作了大部分程序,但我不确定如何输入正确的命令来输入显示定义的键。如果有人可以提供建议,我会很感激!在输入此代码时我也收到了一些错误消息,并且不得不做一堆缩进,不知道我在那里做错了什么。

import random

terms = {"1" : "def 1", #Dictionary of 'terms' and 'definitions'
         "2" : "def 2",
         "3" : "def 3"}

menu = None
while menu != "4":
    print("""

    DIGITAL FLASHCARDS!

    1 - List Terms
    2 - Add Term
    3 - Guess Random Definition
    4 - Exit

    """)
    menu = input("\t\t\tEnter Menu option: ")
    if menu == "1":  # List Terms
        print("\n")
        for term in terms:
            print("\t\t\t", term)
        input("\n\tPress 'Enter' to return to Main Menu.\n")

    elif menu == "2":  # Add Term
        term = input("\n\tEnter the new term: ").upper()
        if term not in terms:
            definition = input("\tWhat is the definition? ")
            terms[term] = definition
            print("\n\t" + term, "has been added.")
        else:
            print("\n\tThat term already exists!")
            input("\n\tPress 'Enter' to return to Main Menu.\n")

    elif menu == "3": # Guess Random Definition. Once correct, choose new random definition
        print("\n\t\t\tType 'Exit' to return to Menu\n")
        choice = random.choice(list(terms.values()))
        print("\n\t" + choice + "\n")

        guess = None
        while guess != "EXIT":
            guess = str(input("\tWhat is the term? ")).upper()

1 个答案:

答案 0 :(得分:4)

  

显示随机定义以尝试并准确猜测。一旦猜到准确,我就可以选择其他定义来猜测

使用terms.items()同时获取密钥和值。

定义在函数generate_question()中生成新定义问题的过程,以避免重复。

elif menu == "3": # Guess Random Definition. Once correct, choose new random definition
    print("\n\t\t\tType 'Exit' to return to Menu\n")
    def generate_question():
        term, definition = random.choice(list(terms.items()))
        print("\n\t" + definition + "\n")
        return term
    term = generate_question()
    guess = None
    while guess != "EXIT":
        guess = input("\tWhat is the term? ").upper()
        if guess == term:
            print("Correct!")
            if input("\tAnother definition?(y/n)").upper() in ["Y", "YES"]:
                term = generate_question()
            else:
                break
  

或者,我希望能够显示随机键:值对,并继续查看对,直到我输入EXIT。

elif menu == "4": # Random display a term-definition pair.
    print("\n\t\t\tType 'Exit' to return to Menu\n")
    exit = None
    while exit != "EXIT":
        term, definition = random.choice(list(terms.items()))
        print(term + ":", definition)
        exit = input("").upper()  # Press enter to continue.

请记住修改开头部分:

while menu != "5":
    print("""

    DIGITAL FLASHCARDS!

    1 - List Terms
    2 - Add Term
    3 - Guess Random Definition
    4 - View term-definition pairs
    5 - Exit

    """)