jeudi 16 novembre 2017

Python 3 - Randomly printing items from dictionary without repeats

I have a modified version of some code I am using in a quiz, my problem is my code is using random.choice to select a quiz question, how do I have it still randomly select a question but also not repeat a question already asked to the user?

Appologies for the odd questions and answers in "quiz_data"

Code:

def InformationToDictionaries():
quiz_data = [
    {
        "question": "What day is it today?",
        "choices": {"a": "Monday", "b": "Friday", "c": "Wednesday", "d": "Sunday"},
        "answer": "Wednesday")
    },
    {
        "question": "What food am I thinking of?",
        "choices": "Pizza", "b": "Curry", "c": "Pie", "d": "Pasta"},
        "answer": "Curry"
    }
]
return quiz_data


def Quiz():
    score = 0
    for i in range(1,6):
        q = random.choice(quiz_data)
        print("Q." + str(i) + ": ", q.get("question"))
        print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
        userans = str(input("\n>"))

    if userans == q.get("answer"):
        print("Correct")
        score = score + 1
    else: print("Incorrect")

quiz_data = InformationToDictionaries()
Quiz()

Many thanks for any responses in advance, if you have any suggestions for me please let me know, this is my first question.




Aucun commentaire:

Enregistrer un commentaire