jo-123
jo-123

Reputation: 11

Simple Python quiz - multiple acceptable answers

I'm a beginner so be kind ;)

I'm making a little quiz and am trying to make it so that it accepts both "js" and "j.s" for question 2, and "four" and "4" for question 3. But I don't know how to do that yet.

Also, I put answer = input(question.prompt).lower() so that it accepts both cases. Would that be the normal way to do it?

Code is very loosely based on a tutorial I saw on YouTube, but please point out my mistakes cos it's all a bit of guesswork at the moment.

# Quiz

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer


question_prompts = [
    "1. Who composed 'O mio babbino caro'?",
    "2. Which Bach composed 'Toccata and Fugue in D minor'?",
    "3. How many movements does Beethoven's Symphony No.5 in C minor have?",
    "4. Complete the title: The .... Danube.",
    "5. Ravel's Boléro featured at the 1982 olympics in which sport?",
    "6. Which suite does ‘In the Hall of the Mountain King’ come from? (2 words)",
    "7. Which instrument is the duck in 'Peter and the Wolf'?",
    "8. Which of these is not a real note value - 'hemidemisemiquaver', 'crotchet', 'wotsit' or 'minim?'"
]

questions = [
    Question(question_prompts[0], "puccini"),
    Question(question_prompts[1], "js"),
    Question(question_prompts[2], "four"),
    Question(question_prompts[3], "blue"),
    Question(question_prompts[4], "ice skating"),
    Question(question_prompts[5], "peer gynt"),
    Question(question_prompts[6], "oboe"),
    Question(question_prompts[7], "wotsit"),

]


def run_quiz(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt).lower()
        if answer == question.answer:
            score += 1

    print()
    print("you got", score, "out of", len(questions))
    if score > 1:
        print("Well done!")
    else:
        print("Better luck next time!")


run_quiz(questions)

Upvotes: 1

Views: 384

Answers (2)

JarroVGIT
JarroVGIT

Reputation: 5314

What you could do is make lists of possible answers like this:

Question(question_prompts[2], ["four", "4"])

Then in your of statement you can do: if answer in question.answer:

This checks if the given answer is in the list of possibilities. Note that I made a string of 4 by using quotes, because the value from an input() is always a string (even if the input is just an number).

Upvotes: 0

flappix
flappix

Reputation: 2217

Instead of single value you can pass an array of acceptable answers to the Question constructor like

questions = [
    Question(question_prompts[1], ["js", "j.s"]),
    Question(question_prompts[2], ["four", "4"]),
    # ...
]

Then you need to change the line

if answer == question.answer:

to

if answer in question.answer:

and you're done.

Upvotes: 1

Related Questions