Bottom Page

Thread Rating:
  • 3 Vote(s) - 4.33 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Multiple expressions with "or" keyword
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": 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.
ThomasL, Mark17, newbieAuggie2019 like this post
I've made this sticky, since it's such a common pitfall.
metulburr likes this post
Feel like you're not getting the answers you want? Checkout the help/rules for things like what to include/not include in a post, how to use code tags, how to ask smart questions, and more.

Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)

Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)