Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'or' in an 'if' statement (Python) [duplicate]

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?

like image 715
JustAkid Avatar asked Feb 17 '26 16:02

JustAkid


1 Answers

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

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

The left part may be false, but the 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!"):
like image 113
blue_note Avatar answered Feb 19 '26 06:02

blue_note



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!