بتل کد Battle Codeدارد باز می‌شود…

Save and Load چالش 4 از جلسه‌ی 13، سخت

قدم ۴: اپ یادش بماند. items را با app.load("money", []) بخوان، در add بعد از اضافه کردن app.save("money", items) بنویس، و show() را پیش از app.run() صدا بزن. بعد از بستن و باز کردن اپ، لیست، مانده و نمودار باید همان باشند.

import app

items = []
GOAL = 100000

def add(kind):
    cat = category.value.strip()
    try:
        amount = int(money.value)
    except ValueError:
        app.toast("Type a real amount")
        return
    if amount <= 0:
        app.toast("Type a real amount")
        return
    if cat == "":
        app.toast("Type a category")
        return
    items.append({"kind": kind, "cat": cat, "amount": amount})
    money.value = ""
    show()

def add_income():
    add("in")

def add_spend():
    add("out")

def show():
    lines.clear()
    balance = 0
    for item in items:
        if item["kind"] == "in":
            lines.add(f"+{item['amount']} {item['cat']}")
            balance = balance + item["amount"]
        else:
            lines.add(f"-{item['amount']} {item['cat']}")
            balance = balance - item["amount"]
    balance_text.value = f"Balance: {balance:,} toman"
    if balance >= GOAL:
        goal_text.value = "Goal reached!"
    else:
        goal_text.value = f"Left to goal: {GOAL - balance:,} toman"
    totals = {}
    for item in items:
        if item["kind"] == "out":
            totals[item["cat"]] = totals.get(item["cat"], 0) + item["amount"]
    chart.update(list(totals.values()), list(totals.keys()))

app.title("Pocket Money")
category = app.input("Category")
money = app.number("Amount")
app.button("Income", add_income)
app.button("Spend", add_spend)
balance_text = app.text("Balance: 0 toman")
goal_text = app.text("Left to goal: 100,000 toman")
chart = app.bar([], [])
lines = app.list()
app.run()

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 13: پروژه: پول توجیبی

بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال