1

I'm new to Python and I was just experimenting with creating a simple calculator, and for some reason a function won't get overwritten. Whatever operator I input, the result will stay the same at 3125.

I tried using the percentage symbol but it is still stuck on one output.

num1 = float(input("First Number: "))
op = input("Operator: ")
num2 = float(input("Second Number: "))

if op == "^" or "**":
    result = float(num1) ** float(num2)
    print("Result: %s" % result)
elif op == "/"or "÷":
    result = float(num1) / float(num2)
    print("Result: %s" % result)
elif op == "x" or "*" or ".":
    result = float(num1) * float(num2)
    print("Result: %s" % result)
elif op == "+":
    result = float(num1) + float(num2)
    print("Result: %s" % result)
elif op == "-":
    result = float(num1) - float(num2)
    print("Result: %s" % result)

Why is it stuck, and why on 3125? This confuses me as I looked into other calculator codes and mine look the same.

  • 1
    Welcome to Stack Overflow! When asking a question, please make sure to include the input you are using as well as your expected output. – Matt Apr 21 '19 at 00:54
  • You want `op in ('^', '**')`, otherwise your first `if` always takes the `True` branch. – gmds Apr 21 '19 at 00:54

1 Answers1

1

Your issue is that you're using the or to be either symbol, but the or needs a boolean operator on each side.

# change this
if op == "^" or "**":
# to this
if op == "^" or op == "**":

Even better is to use the in operator with a list of potential options.

if op in ['^', '**']:

Update your code as follows and you should be good to go! I also removed the redundant lines. So if you want to update it later, you only have to update it once rather than 5 times.

if op in ["^" , "**"]:
    result = float(num1) ** float(num2)
elif op in ["/", "÷"]:
    result = float(num1) / float(num2)
elif op in ["x" , "*" , "."]:
    result = float(num1) * float(num2)
elif op in ["+"]:
    result = float(num1) + float(num2)
elif op in ["-"]:
    result = float(num1) - float(num2)

print("Result: %s" % result)
Cohan
  • 4,384
  • 2
  • 22
  • 40