2

I'm just writing a simple if statement. The second line only evaluates to true if the user types "Good!" If "Great!" is typed it'll execute the else statement. Can I not use or like this? Do I need logical or?

    weather = input("How's the weather? ")
if weather == "Good!" or "Great!": 
    print("Glad to hear!")
else: 
    print("That's too bad!")
JustAkid
  • 109
  • 1
  • 1
  • 8

1 Answers1

12

You can't use it like that. The or operator must have two boolean operands. You have a boolean and a string. You can write

weather == "Good!" or weather == "Great!": 

or

weather in ("Good!", "Great!"): 

What you have written is parsed as

(weather == "Good") or ("Great")

In the case of python, non-empty strings always evaluate to True, so this condition will always be true.

blue_note
  • 27,712
  • 9
  • 72
  • 90
  • 1
    Pretty sure that the `"Great!"` string in the question will just be evaluated as being `True` rather than being an exception – PyPingu Jan 26 '18 at 16:35
  • 1
    @PerlPingu: You're right. I was thinking about the operator in general, forgot it works that way in python. editing... – blue_note Jan 26 '18 at 16:36
  • 1
    Appreciate the help. Why was I given a -1 for this question? I'm clearly new but I think this is a legitimate question. I didn't see a duplicate asked specifically for Python – JustAkid Jan 26 '18 at 16:58
  • Haha, you're clearly new. You can get downvoted for anything here. -1 is not bad, I've had some of mine getting 5-6 downvotes in seconds... – blue_note Jan 26 '18 at 17:04
  • "The or operator must have two boolean operands" is not correct: `("hello" or "world") == 'hello'`, `(1 or 0) == 1`. The `or` operator can be applied to any two objects. – ForceBru Jul 10 '20 at 20:38