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

جواب «Custom Exception» چالش 2 از جلسه‌ی 20

سؤال

کلاس InsufficientFunds را به‌عنوان زیرکلاس Exception تعریف کن. تابع withdraw(balance, amount) اگر مبلغ بیشتر از موجودی بود InsufficientFunds("insufficient funds") پرتاب کند و وگرنه موجودی جدید را برگرداند. دو عدد بخوان (موجودی، مبلغ) و چاپ کن balance: 70 یا error: insufficient funds.

راهنما

class InsufficientFunds(Exception): pass کافی است.

یک جواب درست

class InsufficientFunds(Exception):
    pass


def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFunds("insufficient funds")
    return balance - amount


balance = int(input())
amount = int(input())
try:
    print(f"balance: {withdraw(balance, amount)}")
except InsufficientFunds as e:
    print(f"error: {e}")

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