首页 > 解决方案 > Python中的测验游戏循环

问题描述

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

我在上面创建了question_class.py文件并将其导入到下面的quiz.py文件中。我正在尝试运行一个while循环来询问用户他们是否有兴趣再次参加测验。但是,代码不会运行。

如何在循环中再次正确插入播放?另外,我如何询问用户是否准备好玩游戏并正确检查输入错误?

这是我的第一个个人项目,并在完成初学者教程后尝试学习如何编写自己的项目。我感谢所有反馈。

    from question_class import Question

    username = input("What is your name? ")
    print(f"Welcome, {username}!")

    play_again = 'y'
    while play_again == 'y':

    question_prompts = [
    ]

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

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

    play_again = input("Want to play again(y/n): ")

    run_test(questions)

标签: python

解决方案


你有几个缩进问题。首先让我们摆脱

play_again = 'y'
while play_again == 'y': 

部分,因为它会引发错误。

  1. 如何询问用户是否准备好玩游戏

获取用户输入,如果还没有准备好则退出:

if input("Are you ready?") != "y": exit()
  1. 如何在循环中再次插入播放:

您已经在函数中定义了游戏循环内部的内容run_test()。在你的run_test()let's just return 无论他们是否想再次玩:

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

    return input("Want to play again(y/n): ") == 'y'

然后我们可以构建一个简单的while循环:

play_again = True
while play_again:
    play_again = run_test(questions)
  1. 如何正确检查输入错误?

在当前状态下,您实际上不需要。如果用户输入了无效的输入,if answer == question.answer:将评估为 False,因此他们会自动将问题弄错。


推荐阅读