Why the else statement always runs?

Question:

I’ve been making a basic calculator with Python and I have come across this issue. After the calculations are made, "Invalid Number" always prints.

print("Select an action ")
print("1.) Add")
print("2.) Subtract")
print("3.) Multiply")
print("4.) Divide")
ac = int(input(">>>"))
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))

if ac == 1:
    print(fn + sn)
if ac == 2:
    print(fn - sn)
if ac == 3:
    print(fn * sn)
if ac == 4:
    print(fn / sn)
else:
    print("Invalid Number")
    print("Press enter to continue")
    input()

An example (wrong) output is:

Select an action 
1.) Add
2.) Subtract
3.) Multiply
4.) Divide
>>>1
First number :
>>>2
Second number :
>>>3
5.0
Invalid Number
Press enter to continue

How can I fix that so "Invalid Number" only prints when it should?

Asked By: Eli Richardson

||

Answers:

It has got something to do with how you have structured your code, consider this with if...elif:

print("Select an action ")
print("1.) Add")
print("2.) Subtract")
print("3.) Multiply")
print("4.) Divide")
ac = int(input(">>>"))
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))

if ac == 1:
    print(fn + sn)
elif ac == 2:
    print(fn - sn)
elif ac == 3:
    print(fn * sn)
elif ac == 4:
    print(fn / sn)
else:
    print("Invalid Number")
    print("Press enter to continue")
    input()

Explanation: Before, you were checking for ac == 1 and ac == 4 which cannot both be true, so the second else statement was executed as well. This can be omitted with the if..elif construction: once, one of the earlier comparisons become true, the rest is not executed anymore.

Answered By: Jan

With Python 3.10+ you can use the match statement:

match ac:
    case 1:
        ...
    case 2:
        ...
    case 3:
        ...
    case 4:
        ...
    case _:  # default
        ...

Before Python 3.10

You shoud use elif:

if ac == 1:
    ...
elif ac == 2:
    ...
elif ac == 3:
    ...
elif ac == 4:
    ...
else:
    ...
Answered By: Szabolcs Dombi

If I understand you correctly, you just need to replace second and further if with elif:

if ac == 1:
...
elif ac == 2:
...   
if ac == 3:
...        
if ac == 4:
...        
else:
...

And “Invalid Number” will not be printed after each calculation.

Answered By: ShabashP
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.