lemonadedoge
lemonadedoge

Reputation: 63

python if-elif-else always goes to else

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")

Upvotes: 2

Views: 1101

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52101

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.

Upvotes: 10

Jeff Langemeier
Jeff Langemeier

Reputation: 1018

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")

Upvotes: 2

Related Questions