جواب «One Settings Dictionary» چالش 8 از جلسهی 15
سؤال
همهی تنظیمات در دیکشنری settings هستند و read_number آماده است. تابع save_settings را بنویس: اگر کادر Name (بعد از .strip()) خالی بود پیام Please type your name بده؛ عدد کادر Goal را با read_number(goal_box, 1, 20) بخوان. اگر هر دو درست بودند، settings["name"] و settings["goal"] (به شکل عدد) را عوض کن، با app.save("settings", settings) ذخیره کن، show_hello() را صدا بزن و به صفحهی main برگرد. دکمهها Settings و Save هستند.
راهنما
ترتیب مهم است: اول بررسی اسم (return اگر خالی)، بعد goal = read_number(goal_box, 1, 20) و if goal is None: return. فقط بعد از همهی بررسیها دیکشنری را عوض و ذخیره کن.
یک جواب درست
import app
settings = app.load("settings", {"name": "friend", "goal": 8})
def read_number(box, low, high):
try:
n = int(box.value)
except ValueError:
app.toast("Please type a whole number")
return None
if n < low or n > high:
app.toast(f"Choose a number from {low} to {high}")
return None
return n
def show_hello():
hello.value = f"Hi, {settings['name']}! Goal: {settings['goal']} glasses"
def save_settings():
name = name_box.value.strip()
if name == "":
app.toast("Please type your name")
return
goal = read_number(goal_box, 1, 20)
if goal is None:
return
settings["name"] = name
settings["goal"] = goal
app.save("settings", settings)
show_hello()
app.go("main")
app.screen("main")
app.title("Water")
hello = app.text("")
app.button("Settings", lambda: app.go("settings"))
app.screen("settings")
app.title("Settings")
name_box = app.input("Name", settings["name"])
goal_box = app.number("Goal", settings["goal"])
app.button("Save", save_settings)
show_hello()
app.run()
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن