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 باز شود.
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():
pass
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()
راهنما و جواب این چالش · برگشت به درس جلسهی 16: پروژه: آزمونساز · چالش بعدی: Step 4: Shuffle and Play Again
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال