Build a Budget App Project - Build a Budget App Project

Tell us what’s happening:

  1. The transfer method should create a specific ledger item in the category object passed as its argument.
  2. Printing a Category instance should give a different string representation of the object.
  3. create_spend_chart should print a different chart representation. Check that all spacing is exact. Open your browser console with F12 for more details.

My code keeps failing these three tests but im not sure why or whats going wrong.

Your code so far

    class Category():

    def __init__(self, name):
        self.name = name
        self.ledger = []
        self.total = 0.0
    
    def deposit(self, amount, description = ""):
        self.ledger.append({'amount': amount, 'description': description})
        self.total += amount

    def withdraw(self, amount, description = ""):
        if not self.check_funds(amount):
            return False
        else:    
            self.total += (amount*-1)
            self.ledger.append({'amount': round(amount*-1,2), 'description': description})
        return True


    def get_balance(self):
        return self.total

    def transfer(self, amount, budget):
        if self.withdraw(amount,f'Transfer to {budget.name}'):
            budget.deposit(amount,f'Transfer from {budget.name}')
            return True
        else:
            return False

    
    def check_funds(self, amount):
        if amount > self.total:
            return False
        else:
            return True

    def __repr__(self):
        outputstring = ''
        outputstring += f"{self.name:*^30}\n"
        end = 23
        final = 0.0

        for t in self.ledger:
            if len(t['description']) > 23:
                outputstring += f"{t['description'][0:end]}{t['amount']:>{30 - len(t['description'][0:end])}}\n"  

            elif type(t['amount']) == type(int()):
                a = f"{t['amount']:.2f}"
                outputstring += f"{t['description'][0:end]}{a:>{30 - len(t['description'][0:end])}}\n"

            else:    
                outputstring += f"{t['description']}{t['amount']:>{30 - len(t['description'])}}\n"
            final += t['amount']
        outputstring += f"Total: {final:.2f}"
        
        
        return outputstring
        
                
                




        


food = Category('Food')
entertainment = Category('Entertainment')
food.deposit(1000, 'deposit')
food.withdraw(10.15, 'groceries')
food.withdraw(15.79, 'restaurant and more food for dessert')
clothing = Category('Clothing')
food.transfer(50, clothing)
entertainment.deposit(1000, 'ye')
entertainment.withdraw(60,'i said so')
clothing.withdraw(20,'lol')

#print(food.get_balance())
#print(str(food))




def create_spend_chart(categories):

        
    total_withdraw = 0

    catl = {}

    chartstr = f"Percentage spent by category\n"
    

    for c in categories:
        ctotal = 0
        for i in c.ledger:
            if i['amount'] < 0:
                total_withdraw += i['amount']
                ctotal += abs(i['amount'])

        catl[c.name] = ctotal
    total_withdraw = abs(total_withdraw)

    
    for key in catl:
        percentage = (catl[key]/total_withdraw)*100
        catl[key] = percentage
        
    for p in range(100,-10,-10):    
        if p == 100:
            chartstr += f"{str(p) + '|'}"
        elif p == 0:
            chartstr += f"  {str(p) + '|'}"
        else:
            chartstr += f" {str(p) + '|'}"
        for value in catl.values():           
            if p <= value:
                chartstr += f' o '  
        chartstr += '\n'

    L = len(catl.items())
    chartstr += "    "f"{'-'*(L*3 + 1)}"
    chartstr += "\n"
     
        
    categorylength = 0
    for i in categories:
        if len(i.name) > categorylength:
            categorylength = len(i.name)

    for i in range(categorylength):
        chartstr += "    "
        for n in categories:
            if i < len(n.name):
                chartstr += ' ' + n.name[i] + ' '
            else:
                chartstr += "   "
        chartstr += " \n"


    print(chartstr)
    return chartstr
    
    
    
create_spend_chart([food, entertainment, clothing])

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36

Challenge Information:

Build a Budget App Project - Build a Budget App Project

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Let’s do some debugging!

Let’s open the browser console with F12 to see a more detailed view of the tests.

For the first failed test there is this extra info

self.assertEqual(actual, expected, 'Expected "transfer" method to create a specific ledger item in entertainment object.')
AssertionError: {'amount': 20, 'description': 'Transfer from Entertainment'} != {'amount': 20, 'description': 'Transfer from Food'}

the first element in the assertion error is what comes from your code, the second is the expected value.

so I found where you have created some categories and added some prints to check things:

food.transfer(50, clothing)
print(food.ledger)
print(clothing.ledger)

checking clothing.ledger is interesting: [{'amount': 50, 'description': 'Transfer from Clothing'}]. It should say “Transfer from Food” as this is the Clothing category.

Can you fix this?

i changed the transfer method from budget.name to self.name and now it says ive passed test 11 but test 16 and 17 are still not working im not sure how to pass those as my chart looks correct and im not sure what to do for test 16.

Compare your output of printing the category class to the example, they need to be exactly the same. Share your output here if you need help.

Did you check this output? What does it say?

when i use the browser console i see this but im not exactly sure how to use it to fix my output

The assertion error and diff gives you a lot of information to track down a problem. For example:

AssertionError: 'Year' != 'Years'
- Year
+ Years
?     +

Your output comes first, and the output that the test expects is second.

AssertionError: ‘Year’ != ‘Years’

Your output: Year does not equal what’s expected: Years

This is called a diff, and it shows you the differences between two files or blocks of code:

- Year
+ Years
?     +

- Dash indicates the incorrect output
+ Plus shows what it should be
? The Question mark line indicates the place of the character that’s different between the two lines. Here a + is placed under the missing s .

Here’s another example:

E       AssertionError: Expected different output when calling "arithmetic_arranger()" with ["3801 - 2", "123 + 49"]
E       assert '  3801      123    \n   - 2     + 49    \n------    -----    \n' == '  3801      123\n-    2    +  49\n------    -----'
E         -   3801      123
E         +   3801      123    
E         ?                ++++
E         - -    2    +  49
E         +    - 2     + 49    
E         - ------    -----
E         + ------    -----    
E         ?                +++++

The first line is long, and it helps to view it as 2 lines in fixed width characters, so you can compare it character by character:

'  3801      123    \n   - 2     + 49    \n------    -----    \n'
'  3801      123\n-    2    +  49\n------    -----'

Again, your output is first and the expected output is second. Here it’s easy to see extra spaces or \n characters.

E         -   3801      123
E         +   3801      123    
E         ?                ++++

Here the ? line indicates 4 extra spaces at the end of a line using four + symbols. Spaces are a little difficult to see this way, so it’s useful to use both formats together.

I hope this helps interpret your error!

What I see there is that your bars have the wrong height, maje sure you are calculating them in the right way and that you have them in the right order

Thank you. Using the browser console i was able to complete test 16 but i still cant find my error in the code to fix the chart. Any more advice you could offer?

Same as before. What does your output look like when you test it ?

how do i show my output?

Copy it and paste it into a message here.

You can print it with the example in the instructions:

print(food)
*************Food*************
deposit                 900.00
                       -105.55
Total: 794.45
***********Business***********
deposit                 900.00
                         -33.4
Total: 866.60
********Entertainment*********
deposit                 900.00
                        -10.99
Total: 889.01
*************Food*************
initial deposit        1000.00
groceries               -10.15
restaurant and more foo -15.89
Transfer to Clothing    -50.00
Total: 923.96

Do those withdrawls have descriptions?

Try it with the example data and compare to make sure it’s the same.

food = Category('Food')
entertainment = Category('Entertainment')
food.deposit(1000, 'deposit')
food.withdraw(10.15, 'groceries')
food.withdraw(15.79, 'restaurant and more food for dessert')

Thanks for sharing. It help me a lot.

*************Food*************
deposit                 900.00
for food               -105.55
Total: 794.45
***********Business***********
deposit                 900.00
for business             -33.4
Total: 866.60
********Entertainment*********
deposit                 900.00
for entertainment       -10.99
Total: 889.01

I forgot to add descriptions. But it still looks correct i think.

What did you print here?

Check out this part:

i printed each category like print(food), print(business) etc.

I think i realised what the problem is. My percentage calculation is correct but its under the wrong category. My code iterates through using the first withdrawal not according to the category it was withdrawn from. So how do i make it so the correct percentage is attatched to the correct category?

1 Like

Which error message are you troubleshooting?