Step 4: The Final Score چالش 4 از جلسهی 16، سخت
قدم ۴ از ۴: آخر بازی بهجای Quiz over! بگو Quiz over! Your score: <امتیاز>/<تعداد سؤالها> (تعداد را با len حساب کن) و یک دکمهی /quiz برای بازی دوباره بگذار.
import bot
questions = [
{"q": "What is 2 + 3?", "options": ["4", "5", "6"], "answer": "5"},
{"q": "Which animal says moo?", "options": ["Cat", "Cow", "Duck"], "answer": "Cow"},
{"q": "What colour is the sky on a sunny day?", "options": ["Blue", "Green", "Red"], "answer": "Blue"},
]
memory = {"index": -1, "score": 0}
def ask(i):
bot.buttons(questions[i]["options"])
return questions[i]["q"]
def reply(text):
if text == "/quiz":
memory["index"] = 0
memory["score"] = 0
return ask(0)
i = memory["index"]
if i == -1:
return "Welcome to Quiz Bot! Send /quiz to play."
if text == questions[i]["answer"]:
memory["score"] += 1
result = "Correct!"
else:
result = f"Wrong! The answer is {questions[i]['answer']}."
if i + 1 < len(questions):
memory["index"] = i + 1
return [result, ask(i + 1)]
memory["index"] = -1
return [result, "Quiz over!"]
bot.run(reply)
راهنما و جواب این چالش · برگشت به درس جلسهی 16: پروژه: ربات مسابقه
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال