Build a Budget App Project - Build a Budget App Project

Tell us what’s happening:

SyntaxError: f-string expression part cannot include a backslash

return f"{category_header}\n{'\n'.join(f'{dictionary['description'][:23]}{' '*(30-len(dictionary['description'][:23]) - len(str(dictionary['amount'])[:7]))}{str(dictionary['amount'])[:7]}' for dictionary in self.ledger)}\nTotal: {self.balance}"

My code works perfectly in vscode but now when I copy paste it here, I get syntax error. How do I fix this?

Your code so far

# Budget App
class Category:
    def __init__(self,name):
        self.name = name
        self.ledger = []
        self.balance = 0
        self.amount_spent = 0
    def __str__(self):
        category_header = "*" * 30
        middle = len(category_header) // 2
        start_index = middle - (len(self.name) // 2)
        end_index = start_index + len(self.name)
        category_header = category_header[:start_index] + self.name + category_header[end_index:]    
        return f"{category_header}\n{'\n'.join(f'{dictionary['description'][:23]}{' '*(30-len(dictionary['description'][:23]) - len(str(dictionary['amount'])[:7]))}{str(dictionary['amount'])[:7]}' for dictionary in self.ledger)}\nTotal: {self.balance}"
    def deposit(self,amount,description=""):
        self.ledger.append({'amount': amount, 'description': description})
        self.balance += amount

    def withdraw(self,amount,description=""):
        if self.check_funds(amount):
            self.ledger.append({'amount': -amount, 'description': description})
            self.balance -= amount
            self.amount_spent += amount
            return True
        else:
            return False
        
    def get_balance(self):
        return self.balance

    def transfer(self, amount, category):
        if self.check_funds(amount=amount):
            self.withdraw(amount,f"Transfer to {category}")
            category.deposit(amount,f"Transfer from {category}")
            return True 
        else:
            return False
        
    def check_funds(self, amount):
        if amount <= self.balance:
            return True
        else:
            return False
food = Category('Foods')
food.deposit(1200,"deposit $1000")
food.withdraw(1100,"Groceries")
food.get_balance()
print(food)
auto = Category('Auto')
auto.deposit(1200,"deposit $1000")
auto.withdraw(1200,"Groceries")
auto.get_balance()
print(auto)
gas = Category('Gas')
gas.deposit(1200,"deposit $1000")
gas.withdraw(1200,"Groceries")
gas.get_balance()
print(gas)


#Return the percentage spending chart
def create_spend_chart(categories):
    spent = [category.amount_spent for category in categories]
    percentages = []
    lines = []
    for i in range(len(categories)):#Creates the percentages
        percent = (((spent[i]/sum(spent))*100)//10)*10
        percentages.append(percent)
    for i in range(11):#Initializes the bar chart
        lines.append(f"{(i*10):>3}|")

    for i in range(len(percentages)):
        level = percentages[i] / 10
        if level > 0:
            for i in range(int(level)):
                if lines[i][-1] == 'o':
                    lines[i] += "  o"
                else:
                    lines[i] += " o"
    maxl = max(len(item) for item in lines)
    maxc = max(len(category.name) for category in categories)
    name_lines = ['']*maxc
    for category in categories:
        name = category.name
        for index, letter in enumerate(name):
            if len(name_lines[index]) <= 1:
                name_lines[index] += f"     {letter}"
            else:
                name_lines[index] += f"  {letter}"
    
    
    return f"""Percentage spent by category
{'\n'.join(line for line in reversed(lines))}
{'-'*(maxl+2)}
{'\n'.join(line for line in name_lines)}"""
print(create_spend_chart(categories=[food,auto,gas]))




Your browser information:

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

Challenge Information:

Build a Budget App Project - Build a Budget App Project

I also get a syntax error in Google Collab. Are you sure it’s copied correctly.

It’s quite complex for a single line, maybe you should try simplifying it.

I did some research and it appears that using .format seems to work in this situation rather than putting the values straight into the curly brackets.
I’m not sure whether it’s better to use one over the other, but I guess I will implement .format in the rest of my code and see if it takes it since it doesn’t like my previous code.
Previous

return f"{category_header}\n{'\n'.join(f'{dictionary['description'][:23]}{' '*(30-len(dictionary['description'][:23]) - len(str(dictionary['amount'])[:7]))}{str(dictionary['amount'])[:7]}' for dictionary in self.ledger)}\nTotal: {self.balance}"

New

return "{}\n{}\nTotal: {}".format(category_header,'\n'.join('{}{}{}'.format(dictionary['description'][:23],' ' * (30 - len(dictionary['description'][:23]) - len(str(dictionary['amount'])[:7])),str(dictionary['amount'])[:7]) for dictionary in self.ledger),self.balance)