首页 > 解决方案 > 如果用户不输入“a”、“b”或“c”,我将如何重复这个问题?

问题描述

import sys

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

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) Magneta\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'),
]

def run_test(questions):

    score = 0

    while True:

        for question in questions:
            answer = input(question.prompt)

        if answer == question.answer:
                score += 1
        else:
            print('You did not enter a,b or c. Please try again') 

    print('You got' + str(score) + '/' + str(len(questions)) + 'Correct')

def replay():

    choice = input("Play again? Enter Yes or No")

    if choice == 'Yes':
        run_test(questions)
    else:
        sys.exit(0)
    
run_test(questions)
replay()

如果用户没有输入“a”、“b”或“c”,我试图重复 question_prompt,但我正在努力让它工作。

我知道我需要使用 while 循环,但不确定在哪里使用它。我知道它当前使用的地方是错误的。任何帮助将非常感激。

我如何继续要求用户再次播放,因为目前它只工作一次?

标签: python

解决方案


推荐阅读