Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does not else: run when if is false?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ("+", "-", "*", "/", "**")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading