Why !Not? - First learning project woes

I am extremely new, I am learning on my own. I am creating my first real project, one function of which is a calculator.
I am requesting 2 numbers and an operator from the user. I have some history in Pascal and Delphi from high school so the concept of validating my data before using it is not missed on me.

I have used an if != statement to check my operator is valid before proceeding. It will always run that argument as true and return my error message of invalid operator. I have tested by removing all of my β€œor” checks and just checking if the op is β€œ+”, this seems to work correctly each time. i feel I am misunderstanding the use of or within the if statements.

What am I misunderstanding here?

def calc():
    num1 = float(input("Enter first number: "))
    op = input("Enter operator[+, -, *, /]: ")
    num2 = float(input("Enter first number: "))
    while True:
        try:
            print(num1, op, num2)
            if op != "+" or "-" or "*" or "/":
                print("Invalid operator, please try again")
                print(op)
                calc()
            elif op == "+":
                answer = (num1 + num2)
            elif op == "-":
                answer = (num1 - num2)
            elif op == "*":
                answer = (num1 * num2)
            elif op == "/":
                if num2 != 0:
                    answer = (num1 / num2)
                print("You can not divide by 0. Please try again")
                calc()
            print(answer)
            break
        except ValueError:
            print("You have entered invalid numbers, please try again.")
            calc()

I resolved my issue using the following:

 if op not in ["+", "-", "*", "/"]:
                print("Invalid operator, please try again")
                
1 Like

That is really the cleanest possible way of doing that. The other two options to consider would be:

if(op !== "+" && op !== "-" && op !== "*" && op !== "/") { // Each comparison is done, one by one

The other option, more clean in my opinion, might be a switch/case statement.

switch (op) {
  case "+":
    // handle the plus operator here...
    break;
    // MAKE SURE TO BREAK, or it'll fall through to the default option!
  case "-":
    // handle the minus case.
    break;
  case "*":
    // handle the multiply case.
    break;
  case "/":
    // handle the divide case.
    break;
  
  /* The default case is triggered when NONE OF THE ABOVE FIT! 
   *   In our case, that means op is not + - * /
   */
  default:
    console.log(op+" is an invalid operator. Please try again.");
}

The second version is far more readable, I think. Also, it sanely handles each operator case, then and only then says β€œIN EVERY OTHER CASE, do this.”

Thank you. I wish Python had case statements.

…are you razzing me? or did you miss this was the Python board?

1 Like