Stop while loop if user inputs correct operator

Question:

I just started learning Python yesterday and one of the programs I’m trying to write is a calculator. This segment of code is where I’m having problems. The while loop is supposed to stop when the user inputs any of the math operators but it still asks for input even when the user enters one the correct characters.

What do I need to do to fix this.

    op = None                                 
    while (op != "-" or op != "+" or op != "*" or op != "/"):
        op = input("Enter operator (-, +, *, /):  ")
    print(op)
Asked By: asdfghjkl

||

Answers:

You don’t want or between the conditions, you want and.

Answered By: Ariel Kwiatkowski

A chain of or statements is true as long as one of the conditions is true. You want to use and, which will continue the loop (prompt again) if the operator is not one of those characters.

You could also negate the entire condition, e.g.,

while not (op != "-" or op != "+" or op != "*" or op != "/"):
Answered By: mipadi
  op = None                                 
while op not in ["-","+","*","/"]:
    op = input("Enter operator (-, +, *, /):  ")
print(op)

or

op = None                                 
while (op != "-" and op != "+" and op != "*" and op != "/"):
    op = input("Enter operator (-, +, *, /):  ")
print(op)

your code isnt working because while "op" might be equal to one of your options, its not equal to all the others, and therefore continues the loop

Answered By: Christian Trujillo

The other answers are great, but I wanted to show you a piece of code called the break statement. Here is a more detailed explanation, but basically, a break statement breaks out of an iterative loop like a while loop. Here is how your code would look if you used a break statement:

op = None                                 
while (op != "-" or op != "+" or op != "*" or op != "/"):
  op = input("Enter operator (-, +, *, /):  ")

  if op == "-" or op == "+" or op == "*" or op == "/":
    break

print(op)
Answered By: A.Kumar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.