بتل کد 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.

راهنما

در show() قبل از حلقه balance = 0. داخل حلقه برای in بنویس balance = balance + item["amount"] و برای خرج منها. بعد از حلقه: if balance >= GOAL: ← Goal reached!، وگرنه f"Left to goal: {GOAL - balance:,} 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()
    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"

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()

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن