-1

The function I wrote has an if, else statement. It seems like it ignores the if, else statement completely.

def start():
    task = input("Would you like to begin?\n>>>")
    if task == "Yes" or "yes":
        rate()
    else:
        quit()

No matter what I put in the input it automatically performs the function rate() instead of quit().

1 Answers1

1

Since python conditional expressions are left-associated (read from left to right - there are some exceptions), the condition of your if statement is interpreted as

(task == "Yes") or ("yes")

because == only expects one more expression to the right.

Hence even task == ("Yes" or "yes") would fail, due to the or operator expecting boolean values as input (left and right side). Since bool("Yes") evaluates to True the first object is returned by the or operator, here "Yes". That value is then used in the == comparison.

What you might want to do is:

if task.lower() == "yes"

or

if task in ["Yes", "yes"]

mjoppich
  • 3,207
  • 1
  • 11
  • 13
  • 1
    Nit: not *all* operators are left-associative. `2**3**4` is parsed as `2 ** (3 ** 4)`. Parsing this as `task == ("Yes or "yes")` wouldn't work either, as it would trivially reduce to `task == "Yes"`, ignoring `"yes"` altogether. – chepner May 16 '20 at 17:53
  • Indeed - not all all operators are left-associative - though most are :) – mjoppich May 16 '20 at 17:55
  • But, as I also pointed out, this isn't just a matter of associativity, but of the semantics of both `or` and `==`. – chepner May 16 '20 at 17:57
  • `==` expects one expression to the right. Indeed `("Yes" or "yes") ` evaluates to `Yes`because it is the first value to evaluate to `True` by or (which expects boolean expression to the left and right) - which is also what I pointed out - soon in a more elaborated version. – mjoppich May 16 '20 at 18:08
  • 1
    All binary operators expect an expression on the left and on the right. Associativity is only relevant with operators having the same precedence (like `3 + 5 - 7`). `==` and `or` have *different* precedence, though. – chepner May 16 '20 at 18:51