0
    op = {}
    while op != "+" or "-" or "x" or "/":
        op = str(input("Type in an expression: "))
        print("Invalid")

Output

    Type in an expression: +
    Invalid
    Type in an expression: -
    Invalid
    Type in an expression: /
    Invalid
    Type in an expression: x
    Invalid
    Type in an expression:
    // this bit is the return i get when running the code

This is a simple calculator that allows the user to choose an operator type based on input. I've added the bit of code, and what it returns when I run it. No error messages at all. Any help to get this to work will be greatly appreciated. Also, tell me of any better ways I can improve this piece of code. Thanks so much!

Sanjit Sarda
  • 381
  • 1
  • 4
  • 13
  • `op != '+' or '-'` doesn't group the way you think it does. It is not `op != ('+' or '-')`, it is `(op != '+') or ('-')`, and the latter is always true. – Adam Smith Jan 21 '20 at 04:55
  • Could you explain? Or tell me how i can make this work? – Leland Tan J J Jan 21 '20 at 04:57
  • 1
    `op != '+' or op != '-' or ...`, or else `op not in '+-x/'` – Adam Smith Jan 21 '20 at 04:58
  • This is mainly due to operator precedence. https://www.programiz.com/python-programming/precedence-associativity Here != executes first it will return true or false depend on input then if you put or with any string it will return True . While loop will not end. It will become infinity – saravanan saminathan Jan 21 '20 at 05:08
  • ahh thanks for your explanation. I have a question though, where is the true/false variable stored in? or is it even a variable? – Leland Tan J J Jan 21 '20 at 05:16

2 Answers2

1

You can't do multiple comparisons at once - you would have to specify the op !=... bit repeatedly: while op != "+" and op != "-" and op != "x" and op != "/":

if you're trying to check if something is within a list of options, you can do that directly:

while op not in ("+", "-", "x", "/"):
    op = str(input("Type in an expression: "))
    print("Invalid")
Oliver.R
  • 1,282
  • 7
  • 17
1
op = str(input("Type in an expression: ")) # Ask for expression
while op not in ["+", "-", "x", "/"]: # Whilw op does not belong to this list, which mean that op is not any element form this list.
    print("Invalid") # Print invalid 
    op = str(input("Type in an expression: ")) # ask the person to input the operator again, till they correctly input an operator.

Here is something that should work with explanatory comments

The first line is needed because when you run the first iteration of the while loop, it first prints invalid before even asking for the operator. If you reversed the statements, and put op = str(input("Type in an expression: ")) before print("Invalid"), then It will first ask for an operator and then even if it is correct, it will print Invalid, before checking whether it is correct, thats why we need the first statement.

Sanjit Sarda
  • 381
  • 1
  • 4
  • 13