1

I'm making a simple calculator program in Python, and I'm having trouble understanding why this while loop works only when I am using "and" when checking if the variable is a valid operator. logically, I would expect it to check if the input is "+" OR "-", etc.

Here is the loop:

operator = input("Enter operator: ")
while operator != "+" and operator != "-" and operator != "*" and operator != "/":
    operator = input("Enter a valid operator: ")

I'm especially confused, because it seems to be working as expected in this other loop:

while num1 == "0" or num1.isdigit() == False:
    print("You must enter a valid number that is not 0!")
    num1 = input("Enter first number: ")
Shadow
  • 8,749
  • 4
  • 47
  • 57
  • 1
    `operator != "+" and operator != "-" and operator != "*" and operator != "/"` is equivalent to `not (operator == "+" or operator == "-" or operator == "*" or operator == "/")`. Using `not` to convert between `and` and `or` is done via [De Morgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws). – John Kugelman Oct 09 '18 at 00:44
  • It's because you are using `!=` in the first example and `==`in the second. One is inclusive `==` and the other exclusive `!=`, so they need a different operator to chain them correctly. Taking the `!=` case, if you used `or` then it will always evaluate to true, as it must be unequal to one of the tested values. For `==` it is not correct to use `and` because something cant be equal to more than one thing. – Paul Rooney Oct 09 '18 at 00:56

1 Answers1

2

For Python 3, you can do something along these lines:

operator = input("Enter operator: ")
while operator not in '+-*/':
    operator = input("Enter a valid operator: ")    

And, while you are at it, you might as well test and assign at the same time by using a dictionary and the operator module to avoid a later if then if then ladder:

import operator 

operators={'+':operator.__add__,
           '/':operator.__truediv__,
           '*':operator.__mul__,
           '-':operator.__sub__}

op = input("Enter operator: ")
while op not in operators:
    op = input("Enter a valid operator: ")  

Beware with Python 2 that input preforms an eval against what is typed (with potentially bad consequences.)

If you are using Python 2:

operator = raw_input("Enter operator: ")
while operator not in '+-*/':
    operator = raw_input("Enter a valid operator: ")
dawg
  • 98,345
  • 23
  • 131
  • 206