Using or in if statement (Python) [duplicate]

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!")
1

1 Answer

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.

5

You Might Also Like