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?
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!"):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With