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

The Balance چالش 2 از جلسه‌ی 13، متوسط

قدم ۲: مانده و هدف. GOAL = 100000 و دو متن balance_text و goal_text به صفحه اضافه شده‌اند. در show() مانده را حساب کن (دخل‌ها جمع، خرج‌ها منها) و بنویس:
- balance_text: Balance: 38,000 toman (با {balance:,})
- goal_text: Left to goal: 62,000 toman، یا Goal reached! اگر مانده به هدف رسیده یا بیشتر است.
مثلاً ۵۰۰۰۰ دخل و ۱۲۰۰۰ خرج ← Balance: 38,000 toman و Left to goal: 62,000 toman.

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()
    for item in items:
        if item["kind"] == "in":
            lines.add(f"+{item['amount']} {item['cat']}")
        else:
            lines.add(f"-{item['amount']} {item['cat']}")
    # work out the balance, then show it and what is left to GOAL

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")
lines = app.list()
app.run()

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

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