2

I think there is something wrong with the if-elif-else statement because it always goes to else

#initialize total
total=0.0
#ask for inputs
budget=float(input("Plz Enter amount that you budgeted for a month: "))
expense=float(input("Plz Enter 1st expense - to quit enter 0: "))
while expense!=0:
# Add the expense to the accumulator.
    total += expense
    expense=float(input("Plz Enter a expense - to quit enter 0: "))
#display results
if total>budget:
        print("You are over-budget by",total-budget)
elif budget<total:
        print("You have",budget-total,"to spare")
else:
        print("Your budget is equal to expense")
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
lemonadedoge
  • 63
  • 1
  • 6

2 Answers2

10

Both if and elif are doing the same thing

if total>budget:
    print("You are over-budget by",total-budget)
elif budget<total:
    print("You have",budget-total,"to spare")

It should be:

if total>budget:
    print("You are over-budget by",total-budget)
elif budget>total:
    print("You have",budget-total,"to spare")

But, in order to be cleaner (you will notice the bug easier):

if total>budget:
    print("You are over-budget by",total-budget)
elif total<budget:
    print("You have",budget-total,"to spare")

See how total is now aligned? It is easier to see the difference in operator direction. No thinking required.

Nick Humrich
  • 14,905
  • 8
  • 62
  • 85
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 1
    thanks ill tick the answer in 5minutes I have another question - when i use while expense!='': and then i input blank to end it says cant convert str to float – lemonadedoge Dec 12 '14 at 19:09
  • @LucyY If you have another question, submit another question. – Nick Humrich Dec 12 '14 at 19:10
  • @LucyY Practically speaking, It should be cant convert str to **float** . And for that you can refer to [this](http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-in-python) question – Bhargav Rao Dec 12 '14 at 19:12
2

I would recommend, when doing an if/elif on the same set of variables, to always keep order the same, it increases readability, and is better for error checking. Your brain makes a hard context switch to understand when they aren't in the same order, but the signs are the same, it's non-intuitive.

Your if/elif/else should be the following:

if total > budget:
    print("You are over-budget by",total-budget)
elif total < budget:
    print("You have",budget-total,"to spare")
else:
    print("Your budget is equal to expense")
Jeff Langemeier
  • 1,018
  • 1
  • 10
  • 21