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 هستند.
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():
pass
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()
راهنما و جواب این چالش · برگشت به درس جلسهی 15: تنظیمات و خطاگیری کامل
بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال