python - 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)
解决方案
你有几个缩进问题。首先让我们摆脱
play_again = 'y'
while play_again == 'y':
部分,因为它会引发错误。
- 如何询问用户是否准备好玩游戏
获取用户输入,如果还没有准备好则退出:
if input("Are you ready?") != "y": exit()
- 如何在循环中再次插入播放:
您已经在函数中定义了游戏循环内部的内容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)
- 如何正确检查输入错误?
在当前状态下,您实际上不需要。如果用户输入了无效的输入,if answer == question.answer:
将评估为 False,因此他们会自动将问题弄错。
推荐阅读
- javascript - 如何调试我的鼠标事件处理程序
- networking - ntc-ansible 模块的 SSH 连接问题
- spring-boot - Spring Boot + Mustache:仅在用户通过身份验证时才呈现 html
- case - 案例语句重复行 - teradata
- javascript - 如何在javascript中延迟按钮的输出
- c# - 我该如何扭转这个?- “签名时出错:找不到SignTool.exe”
- python - 用 folium 绘制 netCDF 数据 - python
- android - 排除由 Realm 插件添加的 Gradle 依赖项
- rest - Xpages Domino Rest Services 错误,仅在特定环境中使用键调用 url
- python - 由于在 python 3 中,打印命令的结果不同