Help with budget app

Sorry I’m having problems with the loop… I’m having keyError with the balance function. Thank you very much in advance. Please see my code below

class Category:
def init(self,name):
self.name = name
self.ledger = list()

def balance(self):
    balance = 0
    for i in range(len(self.ledger)):
        balance  += self.ledger[i]['amount']
    return balance

def check_funds(self, amount):
    a = self.balance()
    if amount > a:
        return True
    else: return False

def deposit(self, amount, description = ''):
    self.ledger.append({'amount':amount})
    self.ledger.append({'description':description})

def withdraw(self, amount, description = ''):
    rem_bal = self.balance()
    if amount > rem_bal:
        return False
    else:
        self.ledger.append({'amount':amount})
        self.ledger.append({'description':description})
        return True

def transfer(self, amount, cat):
    newcat = cat.name
    b = self.balance()
    if amount > b:
        return False
    else:
        self.withdraw(-1*amount, f"Transfer to {newcat}")
        self.deposit(amount, f"Transfer from {self.name}")
        return True

def get_balance(self):
    fund = 0
    for u in range(len(self.ledger)):
        fund += self.ledger[u]['amount']
    return fund

You need to change the list append to include amount and description as a single dict element as follows:

    def deposit(self, amount, description=''):
        self.ledger.append({'amount': amount, 'description': description})

    def withdraw(self, amount, description=''):
        rem_bal = self.balance()
        if amount > rem_bal:
            return False
        else:
            self.ledger.append({'amount': amount, 'description': description})
            return True

Thank you very much!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.