Python Forum
Multiple expressions with "or" keyword
Thread Rating:
  • 3 Vote(s) - 4.33 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiple expressions with "or" keyword
#1
Quote:incorrect
if input_value == "Yes" or "yes" or "y" or "Y":

A simple mistake: each expression after a or keyword is a boolean expression. And any string value other than "" is evaluated to True.

So this if statement will pass:
if "Yes":
And so will this:
if "No":
But this won't:
if "":
Introducing the or keyword to separate conditional booleans you need to realize that this passes the if clause:
if "Yes" or "No":
Because both strings evaluate to True. Hence this does the same thing:
if True or True:
Now, you are using the comparison operand (==) in you if clauses. It works the way you have set it without the or keyword:
if value == "Yes":
This passes if value is "Yes". But when you do this:
if value == "Yes" or "Y":
...you are in fact doing this:
if value == "Yes" or True:
And it will always pass. What you want instead is:
if value == "Yes" or value == "Y":
Because both expressions are evaluated to either True or False, and the if clause passes if any of them is True.

As a side-note, this is a more "pythonic" way of doing this sort of thing with the "in" operator:
if value in ("Yes", "Y", "yes", "y", "yay", "jup", "argh"):
Or rather:
yes = ("Yes", "Y", "yes", "y")
if value in yes:
or rather:
value = "Yes"
if value.lower()[0] == 'y':
This will account for all ("Yes", "Y", "yes", "y"). However this will allow input such as "yellow" to slip by.
Recommended Tutorials:


Messages In This Thread
Multiple expressions with "or" keyword - by metulburr - Sep-05-2016, 09:10 PM
RE: Multiple Conditional Expressions - by micseydel - Oct-03-2016, 08:04 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020