JustAkid
JustAkid

Reputation: 195

Using or in if statement (Python)

I have a condition for an if statement. It should evaluate to True if the user inputs either "Good!" or "Great!". The code is as follows:

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

I expect typing "Great!" to print "Glad to hear!", but it actually executes the else block instead. Can I not use or like this? Do I need logical or?

Upvotes: 9

Views: 135820

Answers (1)

blue note
blue note

Reputation: 29099

You can't use it like that. Because of operator precedence, what you have written is parsed as

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

The left part may be false, but right part is true (python has "truth-y" and "fals-y" values), so the check always succeeds.

The way to write what you meant to would be

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

or (in more common python style)

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

Upvotes: 31

Related Questions