Reputation: 930
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?
Upvotes: 2
Views: 2418
Reputation: 43169
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.
Upvotes: 5
Reputation: 5783
match ac:
case 1:
...
case 2:
...
case 3:
...
case 4:
...
case _: # default
...
You shoud use elif
:
if ac == 1:
...
elif ac == 2:
...
elif ac == 3:
...
elif ac == 4:
...
else:
...
Upvotes: 4
Reputation: 578
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.
Upvotes: -1