使用数组进行“quizconstruction”

2024-10-03 21:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在建立一个简单的“测验程序”。此处代码:

import random

wordList1 = []
wordList2 = []

def wordAdd():
    wordNew1 = str(input("Add a word to your wordlist: "))
    wordNew2 = str(input("Add the translation to this word: "))
    if wordNew1 != "exit":
        wordList1.append(wordNew1)
        wordAdd()
    elif wordNew2 != "exit":
        wordList2.append(wordNew2)
        wordAdd()
    else:
        exercise()

def exercise():
    q = random.choice(wordList1)
    a = wordList2
    if q[] == a[]:
        print("Correct!")
    else:
        print("Wrong!")

wordAdd()

我试着检查单词列表1的编号并与单词列表2的编号进行比较。 现在我没想到def练习会起作用,但我找不到让它发挥作用的解决方案。。。 我知道Python中的字典,但我想知道在Python中这样的数组构造是否可行。在

有人能帮我吗?在

提前谢谢!西泽


Tags: toaddinputifdefexitrandomword
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:12

我玩了一点你的代码。我不确定我是否完全理解你的问题,但我按照我认为需要的方式解决了这个问题。我加了一些评论来说明我做了什么。在

我试图坚持你的基本概念(除了递归),但我重命名了很多东西,使代码更具可读性。在

import random

words = []
translations = []

def add_words():
    # input word pairs until the user inputs "exit"
    print('\nInput word and translation pairs. Type "exit" to finish.')
    done = False
    while not done:
        word = raw_input("Add a word to your wordlist: ")
        # only input translation, if the word wasn't exit
        if word != "exit":
            translation = raw_input("Add the translation to this word: ")
        if word != "exit" and translation != "exit":
            # append in pairs only
            words.append(word)
            translations.append(translation)
        else:
            done = True

def exercise():
    # excercising until the user inputs "exit"
    print("\nExcercising starts. ")
    done = False
    while not done:
        # get a random index in the words
        index = random.randrange(0, len(words))
        # get the word and translation for the index
        word = words[index]
        translation = translations[index]
        # ask the user
        answer = raw_input('Enter the translation for "%s": ' % word)
        if answer == "exit":
            done = True
            print("\nGoodbye!")
        elif answer == translation:
            print("Correct!")
        else:
            print("Wrong!")

add_words()
exercise()

相关问题 更多 >