Python中的问答游戏循环

时间:2019-02-08 02:02:46

标签: python

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

我在上面创建了 question_class.py 文件,并将其导入到下面的 quiz.py 文件中。我正在尝试运行一个while循环,以询问用户是否对再次玩测验感兴趣。但是,该代码无法运行。

如何在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)

1 个答案:

答案 0 :(得分:0)

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

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

part,因为它会引发错误。

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

获取用户输入,如果尚未准备就绪,则退出:

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

您已经在函数run_test()中定义了游戏循环中的内容。在您的run_test()中,让我们返回他们是否要再次播放:

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,因此他们只会自动将问题弄错。