I'm a beginner to Python and am struggling with a project I am working on. The program takes monthly income, fixed monthly expenses, asks for any additional expenses, and then outputs with an if else statement. My issue is in this function:
def spending(income, totals):
finalTotal = income - totals
if income > finalTotal:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif finalTotal > income:
print("You overspent by $", "%.2f"%finalTotal, "this month!")
else:
print("You broke even this month!")
It is printing:
You saved $ -805.00 this month!
When I'd like it to print:
You overspent by $ 805.00 this month!
Any feedback would be greatly appreciated!!
Here is my code: https://replit.com/@ashleyshubin/BudgetProgram#main.py
CodePudding user response:
If totals is your monthly expenses, then subtracting totals from income gives you how much money you made this month. The first if statement should be
if finalTotal > 0:
The second if statement would be
if finalTotal < 0:
And you would want to use abs(finalTotal) when printing finalTotal so it does not display a negative number
CodePudding user response:
Your checks are wrong. You can do the following:
def spending(income, totals):
finalTotal = income - totals
if income > totals:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif totals > income:
print("You overspent by $", "%.2f"%-finalTotal, "this month!")
else:
print("You broke even this month!")
CodePudding user response:
This section is where it is going wrong:
finalTotal = income - totals
if income > finalTotal:
print("You saved $", "%.2f"%finalTotal, "this month!")
It looks like you're comparing the wrong variables in your "if" statement. your "finalTotal" variable already includes your income. Think of it like alegbra, and replace "finalTotal" with "income - totals", and your if statement now looks like:
if income > (income - totals):
this statement will always evaluate to true, no matter what values you are using. You probably want to rewrite your if statements to compare "income > totals", rather than finalTotal.
CodePudding user response:
your comparison shoud be based on finaltotal , as fianaltotal is finalTotal = income - totals
, also else
never runs based on the other conditions in your code:
def spending(income, totals):
finalTotal = income - totals
if finalTotal > 0:
print("You saved $", "%.2f" % finalTotal, "this month!")
else:
print("You overspent by $", "%.2f" % abs(finalTotal), "this month!")
CodePudding user response:
you should be comparing Income with total spends.
def spending(income, totals):
finalTotal = abs(income - totals)
if totals < income:
print("You saved $", "%.2f"%finalTotal, "this month!")
elif totals > income:
print("You overspent by $", "%.2f"%finalTotal, "this month!")
else:
print("You broke even this month!")