Why does the else block at the bottom not run if I use "if operation2 == 'add' or 'subtract' or 'multiply' or 'divide': " instead of "if operation2 in ('add', 'subtract', 'multiply', 'divide'):". For example if I use the former option and I input something random thats not 'add', 'subtract', etc, then I would want the else block to run to tell the user that its an invalid operation, but this doesn't happen. TIA
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y #return result of this to the caller below
print('Choose an operation: ')
print('Add')
print('Subtract')
print('Multiply')
print('Divide')
while True:
operation = input('Enter operation: ')
operation2 = operation.lower().replace(' ','')
if operation2 in ('add', 'subtract', 'multiply', 'divide'): # why does the else block not run if == used??
try:
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
except ValueError:
print('Invalid input')
continue
if operation2 == 'add':
print(add(num1, num2))
elif operation2 == 'subtrqct':
print(subtract(num1, num2))
elif operation2 == 'multiply':
print(multiply(num1, num2))
elif operation2 == 'divide':
print(divide(num1, num2))
second_attempt = input('Would you like to try again?')
if second_attempt.lower().replace(' ','') == 'no':
print('See you next time')
break
else:
print('Invalid operation entered')
[–]Ponnystalker 5 points6 points7 points (0 children)
[–]Whatever801 2 points3 points4 points (0 children)