why does if not operation == '/' or '*' or '+' or '-': give me a syntax error,

Viewed 145
if not operation == '/' or '*' or '+' or '-':
  print('not a valid answer, try again')
  operation = (input('Please enter what operation you would like to do, / is divide, * is multiply, + is plus and - is minus')
3 Answers

operation = (input('Please enter what operation you would like to do, / is divide, * is multiply, + is plus and - is minus')

You forgot to add a second closing brace. In this case, just remove the opening brace.

Additionally, your if statement will always be True. Following code will work:

if not operation in ['/', '*', '+', '-']: # test if operation is one of /, *, + and -
  print('not a valid answer, try again')
  operation = input('Please enter what operation you would like to do, / is divide, * is multiply, + is plus and - is minus')

Did you mean something like this? Note the corrected syntax and logic. Use an infinite loop, prompt for the user input before you check that input. Exit from the loop (break) when operation belongs to the set of allowed values. Otherwise, repeat the loop and prompt for the user input again. Use f-strings or formatted string literals to print incorrect input (make the user error easier to see).

while True:
    operation = input('Please enter what operation you would like to do, / is divide, * is multiply, + is plus and - is minus: ')
    if operation in {'/', '*', '+', '-'}:
        break
    print(f'Not a valid answer: {operation}, try again')

Each clause that is broken up by an or statement is its own Boolean.

So if not operation == '/' or '*' or '+' or '-': really represents four different Booleans:

  1. if not operation == '/'
  2. '*'
  3. '+'
  4. '-'

To correct this, you need to write each statement as its own conditional:

  1. if not operation == '/'
  2. if not operation == '*'
  3. if not operation == '+'
  4. if not operation == '-'

Or, strung together,

if not operation == '/' or not operation == '*' or not operation == '+' or not operation == '-'
Related