Eli R - 1 month ago 5x
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.

``````def badnum():
print("Invalid Number")
print("Press enter to continue")
input("")
def main():
print("Select an action ")
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:
print("\n"*100)
while True:
try:
main()
except ValueError:
except ZeroDivisionError:
print("Infinity")
print("\n"*100)
``````

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:
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.