0

So I am trying to make a simple calculator. I want it so when I ask for input on what operation they want for the two numbers they type to be add, subtract, multiply, or divide. If the input for the operation selection isn't anything other than add, subtract, multiply, or divide then I want it to print("Incorrect Operation"). I had this working before but I had to rewrite the whole thing cause I accidentally deleted the file.

Anyways, I try to achieve this by using and if statement using the == sign to check if the input string is any of the following strings. That part works. The part that seems to be failing is the else statement which seems to not be picking up that anything other than the specified strings should do:

print("Incorrect Operation") quit()

The output that I get from the script below does not have any errors but does not do what I just specified (to print something and quit the program). If anyone could help me it would be greatly appreciated!


if function_type == 'add' or 'subtract' or 'multiply' or 'divide':
    print("Correct Operation!")
else:
    print("Incorrect Operation")
    quit()

num_1 = float(input("First Number: "))
num_2 = float(input("Second Number: "))

if function_type == "add":
    print(num_1 + num_2)

if function_type == "subtract":
    print(num_1 - num_2)

if function_type == "multiply":
    print(num_1 * num_2)

if function_type == "divide":
    print(num_1 / num_2)

Select the type of operation (add, subtract, multiply, divide): nworfr

Correct Operation!

vanilla
  • 69
  • 1
  • 2
  • 13
  • 1
    `if function_type == 'add' or 'subtract' or 'multiply' or 'divide':` doesn't mean what you think it means. It is always `True` independent of `function_type`. – John Coleman Aug 20 '19 at 23:38

1 Answers1

1

I'm afraid that is not how boolean expressions work. They seem logical cause it sounds like how you would translate into english but unless you explicitly specify the conditions, the values will be evaluated on their own. You would need to change your condition to:

if function_type == 'add' or function_type == 'subtract' or function_type == 'multiply' or function_type == 'divide':
    print("Correct Operation!")
else:
    print("Incorrect Operation")
    quit()

When you mention the string alone, it will evaluate 'subtract' and not funtion_type == 'subtract'. Since the string is not None, it will always be evaluated to True.

razdi
  • 1,388
  • 15
  • 21