Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need help making an extremely basic quiz

I am going through a beginner Python course and the task is to make a multiple choice quiz. The way the guy on Youtube handled the question "What color are apples?" is he put "Red/Green" as one answer. This doesn’t satisfy me so I want to make two options correct. How do I do that?

Here’s the code where only "a" is correct:

from Student import Question
question_prompt = [
    "What color are apples?\n(a) Red\n(b) Purple\n(c) Green\n\n",
    "What color are bananas?\n(a) Purple\n(b) Yellow\n(c) Blue\n\n"
]

questions = [
    Question(question_prompt[0], "a"),
    Question(question_prompt[1], "b")
]

def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)
        if answer == question.answer:
            score +=1
    print("You got " + str(score) + "/" + str(len(questions)))

run_test(questions)

Here’s the Student file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

As I’m completely new to programming all I could come up with was putting or but from a experienced programmer perspective that must have been pretty silly.

Question(question_prompt[0], "a" or "c")

>Solution :

The cleanest way is to change answer to a list:

questions = [
    Question(question_prompt[0], ["a", "c"]),
    Question(question_prompt[1], ["b"])
]

Then use the in operator:

def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)
        if answer in question.answer:
            score +=1
    print("You got " + str(score) + "/" + str(len(questions)))

If you want to be able to use strings and lists as answer, look into isinstance(answer, str) to change the test accordingly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading