3

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)
asdfghjkl
  • 57
  • 3

3 Answers3

3
  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

  • 1
    The `not in` technique is exactly what I was going to post, but I'd use a `tuple` rather than a `list` as tuples are faster. – BeRT2me Aug 06 '22 at 00:04
  • For some reasons why, you can see [here](https://stackoverflow.com/questions/3340539/why-is-tuple-faster-than-list-in-python) – BeRT2me Aug 06 '22 at 00:06
  • 1
    informative, thankyou, so tuples are built about 3x faster than lists, and tuples made of literals (rather than variables) are built about 6x faster – Christian Trujillo Aug 06 '22 at 00:16
  • Yep, lists are used for their mutability, but if it's not going to be changed, a tuple is better~ – BeRT2me Aug 06 '22 at 00:18
  • You can also use a string: `while op not in "-+*/":` – mipadi Aug 07 '22 at 18:47
  • @mipadi this definitely works but I think strings still have a certain level of complexity to them in python, so tuple would still be better. feel free to correct if im wrong – Christian Trujillo Aug 08 '22 at 16:12
2

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

1

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)
kumarhimself
  • 70
  • 1
  • 10