0

So I am new to coding (starting with python) and I am trying to make a super simple/basic calculator. I've run in to this problem before on another set of code that I can't figure out why. Even though it's false the line of code returns true. So say I did 100 divided by 5, it returns true for "*" and "Multiply" which gives the outcome of 500 instead of the correct answer which should be 20. If someone could explain/show why it's returning true instead of false?

def calculator():
    Number_input_one = int(raw_input("Enter your first number: "))
    Math_symbol = raw_input("What do you want to do? ")
    Number_input_two = int(raw_input("Enter your second number: "))

    if Math_symbol == "*" or "Multiply":
        print Number_input_one * Number_input_two
    elif Math_symbol == "/" or "Divide":
        print Number_input_one / Number_input_two
    elif Math_symbol == "+" or "Add":
         print Number_input_one + Number_input_two
    elif Math_symbol == "-" or "subtract":
        print Number_input_one - Number_input_two
    else:
        print "it doesn't match anything!"
James Mills
  • 18,669
  • 3
  • 49
  • 62

3 Answers3

4

You are making a classic mistake:

if Math_symbol == "*" or "Multiply":

doesn't do what you think it does. The correct version is:

if Math_symbol in ("*", "Multiply"):

What your version of the code is doing is checking if Math_symbol == "*" or if "Multiply" exists (i.e. it is not an empty string). This will always evaluate to True since the string "Multiply" does exist.

Similar corrections are needed for the other if statements:

if Math_symbol in ("*", "Multiply"):
    print Number_input_one * Number_input_two
elif Math_symbol in ("/", "Divide"):
    print Number_input_one / Number_input_two
elif Math_symbol in ("+", "Add"):
     print Number_input_one + Number_input_two
elif Math_symbol in ("-", "subtract"):
    print Number_input_one - Number_input_two
else:
    print "it doesn't match anything!"
sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

You can also try this:

if (Math_symbol == "*") or (Math_symbol=="Multiply"):

elif (Math_symbol == "/") or (Math_symbol == "Divide"):

and so on!

Sharif Mamun
  • 3,508
  • 5
  • 32
  • 51
0

You want math_symbol == "-" or math_symbol == "subtract"

the statement "string" always evaluates true

Bachmann
  • 748
  • 6
  • 12