-1

I'm trying to run the following code:

while check == False:
    op = input('Do you want to add, subtract, multiply or divide?')
    if op != ((('add' or 'subtract') or 'multiply') or 'divide'):
        print('Please enter a valid operation')
    else:
        check = True

However, only 'add' is seen as a valid input. Is there a way to execute this code without using nested if statements so that all 4 options are valid?

Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67
Kornel
  • 11
  • 1
  • 1
    Why not use a set and simply test if the value of *op* exists in that set. It'll avoid nested *if* statements and all this crazy boolean logic. – theabhinavdas Aug 13 '16 at 12:40
  • You need to check the syntax of a language. The `or` binary operator does not work the way you think it works. – Rory Daulton Aug 13 '16 at 13:38

5 Answers5

4

You can do it using the not in operator:

if op not in ['add', 'substract', 'multiply', 'divide']:
    print('Please enter a valid operation')

in checks for an item in a container, not in just does the opposite.


Or additionally, as @Chris_Rands suggests, replace the list by a set for efficiency:

if op not in {'add', 'substract', 'multiply', 'divide'}:
    print('Please enter a valid operation')
Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67
1

You have to make each comparison individually, so op != 'add' and op != 'subtract'....

VortixDev
  • 965
  • 1
  • 10
  • 23
0

or operator is executed before !=. What you doing wrong is that you are working with wrong operands:

'add' or 'substract'
>>> 'add'

This means that in the end it will be:

if 'op' != 'add':

That is exactly what you get. What you need to do is to compare op to each operation you allow:

if (op != 'add') and (op != 'substract'):

or with python-fu

validOperations = ['add, 'substract']
if op not in validOperations:
Teivaz
  • 5,462
  • 4
  • 37
  • 75
0

You can use in and a list.

while check == False:
    op = input('Do you want to add, subtract, multiply or divide?')
    if op not in ['add', 'subtract', 'multiply', 'divide']:
        print('Please enter a valid operation')
    else:
        check = True
MarcoBuster
  • 1,145
  • 1
  • 13
  • 21
0

If you're keen on an answer similar to your code, this works:

check = False
while check == False:
  op = raw_input('add/subtract/multiply/divide ? : ')
  if op != 'add' and op != 'subtract' and op != 'multiply' and op != 'divide':
    print 'What? Choose wisely.'
  else:
    print 'Well chosen.'
    check = True
theabhinavdas
  • 454
  • 4
  • 16