本文目录导读:

我来帮你制作一个交互式问答脚本,以下是几种不同实现方式的示例:
Python 基础问答脚本
def interactive_quiz():
"""基础交互式问答系统"""
questions = [
{
"question": "Python中用于定义函数的关键字是什么?",
"options": ["A. define", "B. def", "C. function", "D. func"],
"answer": "B"
},
{
"question": "列表是可变的还是不可变的?",
"options": ["A. 可变的", "B. 不可变的", "C. 两者都是", "D. 都不是"],
"answer": "A"
}
]
score = 0
print("欢迎参加Python知识问答!")
print("请输入选项字母(A/B/C/D)作答\n")
for i, q in enumerate(questions, 1):
print(f"第{i}题: {q['question']}")
for option in q['options']:
print(option)
user_answer = input("\n你的答案: ").upper()
if user_answer == q['answer']:
print("✅ 回答正确!\n")
score += 1
else:
print(f"❌ 回答错误,正确答案是 {q['answer']}\n")
print(f"问答结束!你的得分:{score}/{len(questions)}")
if score == len(questions):
print("🎉 满分!太厉害了!")
elif score >= len(questions) * 0.6:
print("👍 不错,继续加油!")
else:
print("💪 多加练习,你会更好的!")
# 运行问答
if __name__ == "__main__":
interactive_quiz()
更完善的班级问答系统
import random
import time
class QuizSystem:
"""班级问答系统"""
def __init__(self):
self.students = {}
self.current_question = None
self.question_pool = [
{
"question": "什么是人工智能?",
"time_limit": 30
},
{
"question": "Python的特点有哪些?",
"time_limit": 45
}
]
def register_student(self, name):
"""注册学生"""
if name not in self.students:
self.students[name] = {"score": 0, "answers": []}
print(f"{name} 注册成功!")
else:
print(f"{name} 已经注册过了")
def ask_question(self):
"""提问并收集答案"""
self.current_question = random.choice(self.question_pool)
print(f"\n🤔 问题:{self.current_question['question']}")
print(f"⏰ 思考时间:{self.current_question['time_limit']}秒")
# 模拟计时
time.sleep(2)
print("\n📝 请所有同学输入答案(输入'结束'退出本轮):")
while True:
answer = input(f"你的答案:").strip()
if answer.lower() == '结束':
break
# 这里可以添加答案收集逻辑
print(f"📌 已记录答案:{answer}")
def show_leaderboard(self):
"""显示排行榜"""
print("\n🏆 排行榜")
print("-" * 30)
sorted_students = sorted(
self.students.items(),
key=lambda x: x[1]['score'],
reverse=True
)
for rank, (name, data) in enumerate(sorted_students, 1):
print(f"第{rank}名:{name} - 得分:{data['score']}")
# 使用示例
def main():
system = QuizSystem()
# 注册学生
system.register_student("小明")
system.register_student("小红")
# 提问
system.ask_question()
if __name__ == "__main__":
main()
命令行界面问答系统
import cmd
import sys
class InteractiveQuiz(cmd.Cmd):
"""交互式命令行问答系统"""
intro = """
===================================
🎯 欢迎使用交互式问答系统
===================================
可用命令:
- start: 开始问答
- add: 添加题目
- list: 查看题目列表
- score: 查看得分
- help: 帮助
- quit: 退出
===================================
"""
prompt = ">>> "
def __init__(self):
super().__init__()
self.questions = []
self.score = 0
self.current_index = 0
def do_start(self, arg):
"""开始问答"""
if not self.questions:
print("⚠️ 题库为空,请先用 add 添加题目")
return
print("\n📝 问答开始!输入答案后按Enter继续")
self.current_index = 0
while self.current_index < len(self.questions):
q = self.questions[self.current_index]
print(f"\n第{self.current_index + 1}题: {q['question']}")
for i, option in enumerate(q['options']):
print(f"{chr(65 + i)}. {option}")
answer = input("\n你的答案: ").upper()
if answer == q['answer']:
print("✅ 正确!")
self.score += 1
else:
print(f"❌ 错误,正确答案是 {q['answer']}")
self.current_index += 1
print(f"\n🎯 问答结束!得分: {self.score}/{len(self.questions)}")
def do_add(self, arg):
"""添加题目"""
print("\n添加新题目(输入'取消'可退出):")
question = input("问题: ").strip()
if question.lower() == '取消':
return
options = []
for i in range(4):
opt = input(f"选项{i+1}: ").strip()
if opt.lower() == '取消':
return
options.append(opt)
print("\n选项列表:")
for i, opt in enumerate(options):
print(f"{chr(65 + i)}. {opt}")
answer = input("正确答案 (A/B/C/D): ").upper()
self.questions.append({
"question": question,
"options": options,
"answer": answer
})
print("✅ 题目添加成功!")
def do_list(self, arg):
"""查看所有题目"""
if not self.questions:
print("题库为空")
return
print(f"\n当前题库(共{len(self.questions)}题):")
for i, q in enumerate(self.questions, 1):
print(f"{i}. {q['question']}")
for j, opt in enumerate(q['options']):
mark = "✅" if chr(65 + j) == q['answer'] else ""
print(f" {chr(65 + j)}. {opt} {mark}")
def do_score(self, arg):
"""查看当前得分"""
total = len(self.questions)
if total > 0:
print(f"\n当前得分: {self.score}/{total} ({self.score/total*100:.1f}%)")
else:
print("暂无题目")
def do_quit(self, arg):
"""退出程序"""
print("感谢使用,再见!")
sys.exit(0)
# 运行程序
if __name__ == "__main__":
InteractiveQuiz().cmdloop()
实现要点
基本功能存储**:使用列表或字典存储题目和答案
- 用户输入:使用
input()获取用户答案 - 答案判断:比较用户输入与正确答案
- 计分系统:记录正确和错误的题目数量
进阶功能
- 随机出题
- 计时功能
- 排行榜回顾
- 难度分级
代码优化建议
# 1. 数据持久化 - 保存到文件
import json
def save_questions(questions, filename="questions.json"):
with open(filename, 'w', encoding='utf-8') as f:
json.dump(questions, f, ensure_ascii=False)
# 2. 错误处理
try:
user_input = input("请输入答案:")
except KeyboardInterrupt:
print("\n程序已中断")
sys.exit(0)
# 3. 输入验证
def validate_input(answer, options=['A','B','C','D']):
return answer.upper() in options
选择哪种实现方式取决于你的具体需求:
- 简单测试:使用基础版本
- 教学场景:使用班级系统
- 构建工具:使用命令行版本
需要我针对某个具体场景进行优化吗?
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播