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:
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.