# Why !Not? - First learning project woes

Why !Not? - First learning project woes
0

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(op)
calc()
elif op == "+":
elif op == "-":
elif op == "*":
elif op == "/":
if num2 != 0:
print("You can not divide by 0. Please try again")
calc()
break
except ValueError:
print("You have entered invalid numbers, please try again.")
calc()
``````

I resolved my issue using the following:

`````` if op not in ["+", "-", "*", "/"]:

``````
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