Eli R Eli R - 2 months ago 6
Python Question

(PYTHON3) Else Statement Always Runs [SOLVED]

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 and then the pause happens. I think it has something to do with the newline breaking the if block but I'm not sure.

Any help will be appreciated.
Thanks in advance.

def badnum():
print("Invalid Number")
print("Press enter to continue")
input("")
def main():
print("Select an action ")
print("1.) Add")
print("2.) Subtract")
print("3.) Multiply")
print("4.) Divide")
ac = int(input(">>>"))
if ac == 1:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn+sn
print(a)
if ac == 2:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn-sn
print(a)
if ac == 3:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn*sn
print(a)
if ac == 4:
print("First number :")
fn = float(input(">>>"))
print("Second number :")
sn = float(input(">>>"))
a = fn/sn
print(a)
else:
badnum()
print("\n"*100)
while True:
try:
main()
except ValueError:
badnum()
except ZeroDivisionError:
print("Infinity")
print("\n"*100)

Jan Jan
Answer

No, it has got something to do with how you have written your code, consider this with if...elif:

ac = int(input(">>>"))
if ac == 1:
        print("First number :")
        fn = float(input(">>>"))
        print("Second number :")
        sn = float(input(">>>"))
        a = fn+sn
        print(a)
elif ac == 2:
        print("First number :")
        fn = float(input(">>>"))
        print("Second number :")
        sn = float(input(">>>"))
        a = fn-sn
        print(a)
elif ac == 3:
        print("First number :")
        fn = float(input(">>>"))
        print("Second number :")
        sn = float(input(">>>"))
        a = fn*sn
        print(a)
elif ac == 4:
        print("First number :")
        fn = float(input(">>>"))
        print("Second number :")
        sn = float(input(">>>"))
        a = fn/sn
        print(a)
else:
        badnum()


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.