Kornel - 3 months ago 9

Python Question

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?

Answer

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')
```

Source (Stackoverflow)

Comments