Multiple expressions with "or" keyword - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Tutorials (https://python-forum.io/forum-4.html) +---- Forum: Common pitfalls and what to do (https://python-forum.io/forum-42.html) +---- Thread: Multiple expressions with "or" keyword (/thread-121.html) |
Multiple expressions with "or" keyword - metulburr - Sep-05-2016 Quote:incorrect 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. RE: Multiple Conditional Expressions - micseydel - Oct-03-2016 I've made this sticky, since it's such a common pitfall. |