Build a Budget App Project - "Your code raised an error before any tests could run..."

Tell us what’s happening:

Hello!

“Your code raised an error before any tests could run. Please fix it and try again.”

Can someone help me with this? I can’t see anything wrong.

Your code so far

class Category:

    total_expenses = []

    def __init__(self, name):

        self.name = name
        self.ledger = []
            


###################DEPOSIT#####
    def deposit(self, amount, description=""):
        
        self.ledger.append({"amount": amount, "description": description})

        

####################WITHDRAW###
    def withdraw(self, amount, description=""):

        if self.check_funds(amount):

            self.ledger.append({"amount": -amount, "description": description})

            return True
            
        else:
            return False



###############GET_BALANCE#####
    def get_balance(self):

        total = 0

        for amount in self.ledger:
            total += float(amount['amount'])

        return total



#############TRANSFER##########
    def transfer(self, amount, another_category):

        if self.check_funds(amount):
            self.withdraw(amount, f'Transfer to {another_category.name}')
            
            another_category.deposit(amount, f'Transfer from {self.name}')

            return True

        else:
            return False



##################CHECK_FUNDS##
    def check_funds(self, amount):

        #se o dinheiro para retirar ou para transferir for maior que o total disponível:
        
        if float(amount) > self.get_balance():
            return False
        else:
            return True


##############PERCENTAGE#######
    def get_expenses(self):
        
        expenses = 0

        for x in self.ledger:
            val = x["amount"]
            if val < 0:
                expenses += -val
        expenses = round(expenses, 2)

        Category.total_expenses.append(expenses)
        
        return Category.total_expenses



######################STRING###
    def __str__(self):

        amount = ''
        description = ''
        output = f'{self.name.center(30, "*")}\n'

        for q in self.ledger:
            amount = "{:.2f}".format(q["amount"])[:7]
            description = q["description"][:23]

            #if description == "deposit":
                #description = "initial deposit"

            output += f'{description.ljust(23)[:23]}{amount.rjust(7)[:7]}\n'

        
        return output + f'Total: {"{:.2f}".format(self.get_balance())}'


####################MAGIC######
    def __repr__(self):
        
        return f'\n\nTotal Expenses: {self.get_expenses()}\n'
        

###############################

food = Category("Food")
food.deposit(1000, "deposit")
food.withdraw(10.15, "groceries")
food.withdraw(15.89, "restaurant and more food for dessert")
clothing = Category("Clothing")
food.transfer(50, clothing)
clothing.withdraw(23.44, "pants")
clothing.withdraw(18.22, "blouse")
entertainment = Category("Entertainment")
entertainment.deposit(500, "deposit for fun")
entertainment.withdraw(12.05, "cinema")
entertainment.withdraw(24.55, "meeting")
entertainment.transfer(120, clothing)
print(food)
print(clothing)
print(entertainment)


###############################

def create_spend_chart(categories):

    if len(categories) > 4:
        return "Impossible! Up to four categories!"

###############################
###############################

    percentages = []
    food_percent = 0
    clothing_percent = 0
    business_percent = 0
    enter_percent = 0

    expenses_val = Category(categories).get_expenses()
    # [76.04, 41.66, 156.6, 0]

    expenses_cat = []

    total_expenses = sum(expenses_val)
    #print(f'\n\nTotal expenses:              ${"{:.2f}".format(total_expenses)}')
###############################

    for category in categories:
        expenses_cat.append(category)
        
    #print(expenses_cat) 
    #print(expenses_val)

    for category in expenses_cat:

        if category == "Food":
            
            expenses_val[0] = "{:.2f}".format(expenses_val[0])
            
            #print(f'Food expenses: ${expenses_val[0]}')
            
            food_percent = round(((float(expenses_val[0])*100)/float(total_expenses))/10)*10

            percentages.append(food_percent)

        elif category == "Clothing":

            expenses_val[1] = "{:.2f}".format(expenses_val[1])
            
            #print(f'Clothing expenses: ${expenses_val[1]}')

            clothing_percent = round(((float(expenses_val[1])*100)/float(total_expenses))/10)*10

            percentages.append(clothing_percent)


        elif category == "Entertainment":

            expenses_val[2] = "{:.2f}".format(expenses_val[2])
            
            #print(f'Entertainment expenses: ${expenses_val[2]}')

            enter_percent = round(((float(expenses_val[2])*100)/float(total_expenses))/10)*10

            percentages.append(enter_percent)

            
        elif category == "Business":

            expenses_val[3] = "{:.2f}".format(expenses_val[3])
            
            #print(f'Business expenses: ${expenses_val[3]}')

            business_percent = round(((float(expenses_val[3])*100)/float(total_expenses))/10)*10

            percentages.append(business_percent)


        else:
            print("Category not included!!")

    # calculate percentage:

    # 274.30 = 100%
    # 76.04  =  ?

    # (274.30)x = 76.04 * 100
    # (274.30)x = 7604
    #     x     = 7604 ÷ 274.30
    #     x     = 27.72 ~ 28 %
    # The answer is: 28%

    print(f'Food expenses: {food_percent}%\nClothing expenses: {clothing_percent}%\nEntertainment expenses: {enter_percent}%\nBusiness expenses: {business_percent}%')



###############################
    #chart = "Percentage spent by category\n"



#####CALLING THE FUNCTION######
create_spend_chart(['Food', 'Entertainment', 'Business', 'Clothing'])



Your browser information:

User Agent is: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Mobile Safari/537.36

Challenge Information:

Build a Budget App Project - Build a Budget App Project

When did you start getting this error?

Did you write all of this code and it never ran, or you passed some tests at one point?

Don’t hardcode values like this:

if category == "Food":

Your function will need to work for ANY value a user adds, like “vacation”

1 Like

If I remove the create spend chart function it’s fine. So the problem is in that function.

I’m adding code back into the function bit by bit, and I get an error here:

Traceback (most recent call last):
  File "main.py", line 198, in <module>
  File "main.py", line 158, in create_spend_chart
ZeroDivisionError: float division by zero

Line 158:

food_percent = round(((float(expenses_val[0])*100)/float(total_expenses))/10)*10

Also:
It looks like you have hard-coded conditionals or variables that check for specific expected values.

if category == "Food":

That is not solving this problem in the general case. Imagine if you were given different input values. Would your code be able to solve those problems?

To find out more about what hard-coding is or about why it is not suitable for solving coding questions, please read this post: Hard-coding For Beginners

Let us know if you have a question about how to make your code more flexible.

Thank you for your attention and help, @pkdvalis!

Yes, I know about the conditional and its “restrict approach” in my writing. Well, right before doing my current “create_spend_chart” function, I was pulling my hair out (for weeks and weeks) in the same !&@^#^$@!! (bad word) function, WITHOUT that kind of conditional (restrict way or “if something == ‘lalalala’”, for example). My approach was suitable for all kind of categories. But, I couldn’t get the right values whenever I changed the category’s position inside categories’ list.

My p. in the a. (ugly expression, sorry) is this function.

I couldn’t take the class Category values to calculate the right percentage and all about. I know how to calculate, doing math and such… but I couldn’t get the right way/approach to calculate each category’s percentage using Python. I tried to import math library, but after, I’ve received that error message. Everything was printed right, but I couldn’t grasp the tests’ results because of that error msg.

1 Like

@pkdvalis , I know how to calculate math. My problem is getting the right way to receive values from class Category and to introduce all the necessary values into the create_spend_chart function. Before my current error, I wrote correctly (50%), but everytime I changed the category’s position inside categories’list, I received wrong results. For example:

create_spend_chart([“Food”, “Auto”, “Business”])

Category food has 30 percent, Category auto has 10 percent and Business has 80 percent.

Now, I’m going to call that function again:

create_spend_chart([“Auto”, “Entertainment”, “Food”])

Before the current approach (or "hard-coding way), the function returned this: 30, 10, 80.

I don’t know if you can understand my English explanation. My first language is Portuguese and I’m not fluent in English.

So, my concern is:

how to get the right values from class Category without getting AttributeError (‘str’) or not being able to calculate the right percentage for each category inside categories’ list?!

how to receive correct values even if I change the Food’s position or Clothing’s position inside categories’ list?!

Budget App has made me “losing all my hair” :crying_cat_face:

Why does the position matter? Changing the position should not change the values. I’ll look into it a bit deeper to see where the problem is, but you’ll likely need to rewrite this whole function.

On the good side, at least you know everything else works well. :+1:

If I copy all of your code again and I add a print here:

            print(float(total_expenses))
            food_percent = round(((float(expenses_val[0])*100)/float(total_expenses))/10)*10

I get this error again:

0.0

---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-11-14e6cbb41a03> in <cell line: 2>()
      1 #####CALLING THE FUNCTION######
----> 2 create_spend_chart(['Food', 'Entertainment', 'Business', 'Clothing'])

<ipython-input-9-06b57bd80485> in create_spend_chart(categories)
     36             #print(f'Food expenses: ${expenses_val[0]}')
     37             print(float(total_expenses))
---> 38             food_percent = round(((float(expenses_val[0])*100)/float(total_expenses))/10)*10
     39 
     40             percentages.append(food_percent)

ZeroDivisionError: float division by zero

This is likely the error that is occurring before the test can run. This needs to be fixed, can’t really proceed here.

I would also remove all rounding for now. You are at least rounding twice, you should save that for the very end. You round here:

def get_expenses(self):
    expenses = round(expenses, 2)

And again in the above calculation. I would round only once, at the very end. I’ll see what else I can find.

The height of each bar should be rounded down to the nearest 10.

And just to keep in mind the bar chart needs to be rounded down, so round() will not do that.

You need a different approach here and you need to print out your variables so you can see if they are working or not:

    print("get expenses:",Category(categories).get_expenses())
    expenses_val = Category(categories).get_expenses()
    print("expenses_val", expenses_val)
    # [76.04, 41.66, 156.6, 0]

    expenses_cat = []

    total_expenses = sum(expenses_val)
    print("total_expenses", total_expenses)
create_spend_chart(['Food', 'Clothing'])
get expenses: [0]
expenses_val [0, 0]
total_expenses 0
0.0

If you code this in a different editor like Google Colab or VSCode you would have seen this error immediately. The fCC editor does not really give the best feedback.

1 Like

This isn’t working because here is your function call:

create_spend_chart(['Food', 'Clothing'])

It’s passing the string "Food". That’s just a string word, not a category object. The category object is food

`Category("Food").get_expenses()`

This isn’t how you would access the get_expenses() method of the food object. It would be food.get_expenses()

I think you also want this to be in a loop iterating through categories:

expenses_val = Category(categories).get_expenses()

I hope this helps!

1 Like

I couldn’t use math.floor(), because the error (I wrote about this previously; it’s when I tried to import math library; using math.floor() without math library didn’t work in my FCC console).

The position was important in my previous function, not the current one.

I’ll try your help explanation.

:+1:

How could you achieve the same effect without using floor()?

@pkdvalis

I haven’t started to write the create_spend_chart() yet (and again, my 3rd time to start it).

I’m going to answer you what I’ve found and read through Google. “Altcademy” says about divmod(), int() and math.floor().

I’ve already used divmod() in another different exercise.

divmod() and int() :thinking:

math.floor() actually it seems you can use it in the fCC editor. But it just rounds down to the nearest integer. You want to round down to the nearest tenth.

You want 36 to become 30.

You could do it just using int() and dividing and multiplying by 10.