1

Why does "Invalid Operator" print when the if statement is false? Could I use an elif statement to make it work?

num1 = float(input("Enter the first number: "))
operator = input("Enter your operator here: ")
num2 = float(input("Enter your second number here: "))


if operator == "+":
    print(num1 + num2)

if operator == "-":
    print(num1 - num2)
if operator == "*":
    print(num1 * num2)
if operator == "/":
    print(num1 / num2)
if operator != ("+", "-", "*", "/"):
    print("Invalid Operator.")


Lance
  • 21
  • 1
  • 6

4 Answers4

3

You are compairing an operator to a tuple. Instead, you can check if operator in tuple, like this:

if operator not in ("+", "-", "*", "/"):
    print("Invalid Operator.")
Arseniy
  • 680
  • 5
  • 10
1

The alternative is elifs:

if operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
elif operator == "/":
    print(num1 / num2)
else:
    print("Invalid Operator.")

With this, when you add a new operator you don't need to modify the not in (...) condition.

khachik
  • 28,112
  • 9
  • 59
  • 94
1

The last if-statement is not correct. Now it checks if it is equal to the entire tuple. You could check if the operator is not in the list.

num1 = float(input("Enter the first number: "))
operator = input("Enter your operator here: ")
num2 = float(input("Enter your second number here: "))


if operator == "+":
    print(num1 + num2)
if operator == "-":
    print(num1 - num2)
if operator == "*":
    print(num1 * num2)
if operator == "/":
    print(num1 / num2)
if operator not in ("+", "-", "*", "/"):
    print("Invalid Operator.")

Another option is indeed using elif and else. If it’s not one of the first for options, then in will be an Invalid Operator (else).

if operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
elif operator == "/":
    print(num1 / num2)
else:
    print("Invalid Operator.")

Edit: Changed if not in ... from list to tuple. Tuples are more efficient in this context.

Niels Henkens
  • 2,553
  • 1
  • 12
  • 27
0
operator != ("+", "-", "*", "/") # condition_1

where operator is a string object, where as ("+", "-", "*", "/") is a tuple so both are not equal so above condition_1 result into True and last if block will get executed. Either use if/elif/else statement or change last condition correctly like this

operator not in ("+", "-", "*", "/") # itemwise ckech takeplace 
operator not in "+-*/" # string is also a iterable object
Davinder Singh
  • 2,060
  • 2
  • 7
  • 22