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

جواب «Pocket Money Report» چالش 8 از جلسه‌ی 17

سؤال

تابع add آماده است. تابع report را بنویس (دکمه‌ی Report). اگر هنوز خرجی نبود، پیام Nothing to report yet بدهد. وگرنه گزارشی بسازد: برای هر خرج یک خط مثل Pen: 5 و خط آخر Total: 17. همین متن را هم در فایل report.txt بنویسد (با open) و هم با app.download("report.txt", text) به کاربر بدهد. کادرها Item و Price و دکمه‌ی دیگر Add است.

راهنما

اول if len(spending) == 0: با پیام و return. بعد lines و total = 0؛ در حلقه هم خط را اضافه کن و هم total = total + s["price"]. بعد از حلقه lines.append(f"Total: {total}"). آخر with open(...) و app.download(...) با همان text.

یک جواب درست

import app

spending = []

def add():
    item = item_box.value.strip()
    if item == "":
        app.toast("Type what you bought")
        return
    try:
        price = int(price_box.value)
    except ValueError:
        app.toast("Please type the price as a whole number")
        return
    spending.append({"item": item, "price": price})
    items.add(f"{item}: {price}")
    item_box.value = ""
    price_box.value = ""

def report():
    if len(spending) == 0:
        app.toast("Nothing to report yet")
        return
    lines = []
    total = 0
    for s in spending:
        lines.append(f"{s['item']}: {s['price']}")
        total = total + s["price"]
    lines.append(f"Total: {total}")
    text = "\n".join(lines)
    with open("report.txt", "w", encoding="utf-8") as f:
        f.write(text)
    app.download("report.txt", text)

app.title("Pocket Money")
item_box = app.input("Item")
price_box = app.number("Price")
app.button("Add", add)
items = app.list()
app.button("Report", report)
app.run()

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