-2
var1 = float(input("Variable 1:"))
operator = input("Write your operator:")
if operator == "+" or "/" or "*" or "-" or "**":
    var2 = float(input("Variable 2:"))
    if operator == "+":  # Addition
        print(f"{var1} + {var2} = ")
        print(var1+var2)
    elif operator == "*":  # Multiplication
        print(f"{var1} * {var2} = ")
        print(var1 * var2)
    elif operator == "/":  # Division
        print(f"{var1} / {var2} = ")
        print(var1/var2)
    elif operator == "-":  # Subtraction
        print(f"{var1} - {var2} = ")
        print(var1 - var2)
    elif operator == "**":  # Power
        print(f"{var1} ** {var2} = ")
        print(var1 ** var2)
else:
    print("Invalid operation, enter a correct operator")

I have just started to programme in Python and I have decided to create a calculator that does basic mathematical operations. It is supossed to work correctly when I put the correct symbol into the "operator" variable, but when I put some random letter it does not run the command "else". Why does this happen?

  • 1
    Python is not English. `or` does not mean what you think it means. – Peter Wood Jun 25 '22 at 11:04
  • 2
    You want to check whether `operator` is in a `set`: `if operator in {"+", "/", "*", "-", "**"}` – Peter Wood Jun 25 '22 at 11:05
  • Does this answer your question? [Python's equivalent of && (logical-and) in an if-statement](https://stackoverflow.com/questions/2485466/pythons-equivalent-of-logical-and-in-an-if-statement) – Christoph Rackwitz Jun 27 '22 at 08:00

4 Answers4

3

You're applying the wrong logic in the code

operator == "+" or "/" or "*" or "-" or "**" is just comparing operator and + symbol, Ignoring rest operators

Correct way is

if operator == "+" or operator == "-" or operator == "*" or operator == "/" or operator = "**

I'll implement this like

if operator in ("+", "-", "*", "/", "**")
Sidharth Mudgil
  • 1,293
  • 8
  • 25
1

You can use in operator in this case to check if the operator is correctly written by the user:

if operator in {"+", "/", "*", "-", "**"}:
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
0

You need to use () for better understanding man. you can get your concept by using like this

if operator == ("+" or "/" or "*" or "-" or "**"):
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
ecemsm
  • 1
  • 1
0
operator == "+" or "/"

will always evaluate to True in the if expression, because the second operand "/" will be implicitly casted to True (as any other non-empty string).

klimenkov
  • 347
  • 2
  • 8