Beginner Python question, issue using "or" and "if" together

Question:

I am using Python to create a very basic calculator. for whatever reason the numbers will only add – they will not do any of the other functions. Please help!

equation_type = input("What kind of math do you want to do? ")
equation_type = equation_type.lower()

first_number = float(input("What is the first number? "))
second_number = float(input("What is the 2nd number? "))

if equation_type == "add" or "addition":
        result = first_number + second_number
elif equation_type == "subtract" or "subtraction":
        result = (first_number - second_number)
elif equation_type == "multiply" or "multiplication":
        result = first_number * second_number
elif equation_type == "divide" or "division":
        result = first_number / second_number
else:
        print("not a valid entry :/")
print(result)
Asked By: Michael Agunga

||

Answers:

The conditions should be like (one of many ways of doing it):

equation_type == "add" or equation_type == "addition":

When checking multiple conditions you need to repeat the equality. There are other ways but since you are in a beginner course you should try to make this one work.

Do the same with the other conditions and see if it works.

Answered By: DeusDev

equation_type == "add" or "addition" does not do what you think it does.

It’s tempting to read Python code as if it were English. It is not! Python is still a programming language, and programming languages have strict rules.

The expression equation_type == "add" or "addition" is parsed as (equation_type == "add") or "addition". The first part, (equation_type == "add") might be true or false depending on the user’s input. However, the second part "addition" is always true from the perspective of if.

Therefore Python always uses the first branch in your if/elif/else chain, and ignores the others, because the first branch is always "true" from its perspective!

The or operator has only one purpose: it combines expressions using logical disjunction. It does not repeatedly apply an equality check for multiple values! Refer to the official documentation for details on what operators like or and and can and cannot do.

You probably wanted to write if equation_type in ("add", "addition"):. The in operator checks whether a value is an element of some collection:

x = "apple"

if x in ("carrot", "celery"):
    print("vegetable")
elif x in ("apple", "pear"):
    print("fruit")

The in operator works on all kinds of collections: tuples (a, b, c), lists [a, b, c], and the keys (not values!) of dictionaries {a: 1, b: 2}.

Answered By: shadowtalker
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.