Using or in if statement (Python)

Question:

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!")
Asked By: JustAkid

||

Answers:

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.

Answered By: blue_note
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.