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

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

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

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 17: فایل‌ها و خروجی

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