جواب «Step 3: Check and Score» چالش 3 از جلسهی 16
سؤال
قدم ۳ از ۴: صفحهی score با متن result اضافه شده. تابع check_answer() (دکمهی Check) را بنویس. جواب کادر Your answer را با .strip().lower() بخوان؛ اگر خالی بود پیام Type an answer first بده و همانجا بمان. اگر با جواب درست (آن هم .lower()) یکی بود، score یکی زیاد شود و پیام Right! بیاید؛ وگرنه پیام Wrong! The answer is 5 (با جواب درست). بعد index یکی زیاد شود. اگر سؤالی مانده، show_question()؛ وگرنه result بشود Score: 2 of 2 و صفحهی score باز شود.
راهنما
این همان فلوچارت است. اول global index, score. جواب درست: right = questions[index]["a"]. بعد از if/else بنویس index = index + 1 و بعد if index < len(questions):.
یک جواب درست
import app
questions = app.load("questions", [])
index = 0
score = 0
def show_questions():
qlist.clear()
for item in questions:
qlist.add(f"{item['q']} = {item['a']}")
def add_question():
q = q_box.value.strip()
a = a_box.value.strip()
if q == "" or a == "":
app.toast("Write a question and its answer")
return
questions.append({"q": q, "a": a})
app.save("questions", questions)
q_box.value = ""
a_box.value = ""
show_questions()
def show_question():
progress.value = f"Question {index + 1} of {len(questions)}"
question.value = questions[index]["q"]
answer_box.value = ""
def start_quiz():
global index, score
if len(questions) == 0:
app.toast("Make some questions first!")
return
index = 0
score = 0
show_question()
app.go("play")
def check_answer():
global index, score
typed = answer_box.value.strip().lower()
if typed == "":
app.toast("Type an answer first")
return
right = questions[index]["a"]
if typed == right.lower():
score = score + 1
app.toast("Right!")
else:
app.toast(f"Wrong! The answer is {right}")
index = index + 1
if index < len(questions):
show_question()
else:
result.value = f"Score: {score} of {len(questions)}"
app.go("score")
app.screen("make")
app.title("Quiz Maker")
q_box = app.input("Question")
a_box = app.input("Answer")
app.button("Add question", add_question)
app.button("Play", start_quiz)
qlist = app.list()
app.screen("play")
app.title("Quiz")
progress = app.text("")
question = app.text("")
answer_box = app.input("Your answer")
app.button("Check", check_answer)
app.screen("score")
app.title("Score")
result = app.text("")
show_questions()
app.run()
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن