python – 如果传递特定输入并尝试跳过代码结束,请立即尝试重新启动方法

我是
python的新手,如果给出了错误的输入,我试图实现强制重启功能(来自e-z的任何字母,包括e和z)

from Question import Question

incorrect_input = False
incorrect_final = False
exit_test = False
question_prompts = [
    "What colors are pears?\n(a) Red\n(b) Blue\n(c) Green\n(d) Yellow",
    "What colors are bananas?\n(a) Yellow\n(b) Blue\n(c) Green\n(d) Red",
    "What colors are apples?\n(a) Blue\n(b) Yellow\n(c) Red/Green\n(d) Orange"
]

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


def exec_test(questions):
    score = 0
    incorrect_input = False
    incorrect_final = False
    exit_test = False
    for question in questions:
        answer = input(str(question.prompt) + "\nEnter your answer: ")
        if answer == question.answer and answer.lower() not in "efghijklmnopqrstuvwxyz":  # incorrect input check
            print("Correct Answer!\n")
            score += 1  # increments score by one if correct
        elif answer != question.answer and answer.lower() not in "efghijklmnopqrstuvwxyz":  # incorrect input check
            print("Incorrect Answer!\n")
        else:
            print("You entered an incorrect form of input! Try again.\n")
            incorrect_input = True  # sets a boolean to True which eventually restarts the quiz
            incorrect_final = True
            exit_test = True
            return incorrect_final
    if exit_test is True:
        return None
    if incorrect_final is True:
        exec_test(questions)
    print("Final Score: " + str(score) + "/" + str(len(questions)) + " correct!")  # final score output


exec_test(questions)

如何让它丢弃测验的所有先前答案,并在每次传递不需要的输入时重新启动方法?

最佳答案 使用for – else

answers = []
passed = False
while not passed:
    for question in questions:
        answer = input('Enter your answer')
        if (not is_valid_answer(answer)):
            # Start over.
            answers = []
            break
        answers.append(answer)  # or whatever
    else:
        passed = True  # Didn't break, therefore passed.
handle_answers(answers)
点赞