[Solved] infinite loop until one of three conditions is True. Python


You can add an if condition inside an infinite while loop to break out of it.

Also your run_test() function must return the score, see below:

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

def run_test(questions):
    score = 0
    for question in questions:
        while True:
            answer = input(question.prompt)
            if answer in ['a', 'b', 'c']:
                break

        if answer == question.answer:
            score +=1

    return score

question_prompts = ['What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n\n',
                    'What color are Bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n\n',
                    'What color are Strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n\n']

questions = [Question(question_prompts[0], 'a'),
             Question(question_prompts[1], 'c'),
             Question(question_prompts[2], 'b')]

score = run_test(questions)
print("\nYou got {}/{} correct".format(score, len(questions)))

Sample Output:

What color are apples?
(a) Red/Green
(b) Purple
(c) Orange

a
What color are Bananas?
(a) Teal
(b) Magenta
(c) Yellow

b
What color are Strawberries?
(a) Yellow
(b) Red
(c) Blue

c

You got 1/3 correct

3

solved infinite loop until one of three conditions is True. Python