How to test multiple variables for equality against a single value?
You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:
if x == 1 or y == 1 or z == 1:
x
and y
are otherwise evaluated on their own (False
if 0
, True
otherwise).
You can shorten that using a containment test against a tuple:
if 1 in (x, y, z):
or better still:
if 1 in {x, y, z}:
using a set
to take advantage of the constant-cost membership test (i.e. in
takes a fixed amount of time whatever the left-hand operand is).
Explanation
When you use or
, python sees each side of the operator as separate expressions. The expression x or y == 1
is treated as first a boolean test for x
, then if that is False, the expression y == 1
is tested.
This is due to operator precedence. The or
operator has a lower precedence than the ==
test, so the latter is evaluated first.
However, even if this were not the case, and the expression x or y or z == 1
was actually interpreted as (x or y or z) == 1
instead, this would still not do what you expect it to do.
x or y or z
would evaluate to the first argument that is 'truthy', e.g. not False
, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).
So for the values x = 2; y = 1; z = 0
, x or y or z
would resolve to 2
, because that is the first true-like value in the arguments. Then 2 == 1
would be False
, even though y == 1
would be True
.
The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3
would fail for the same reasons. Use x == 1 or x == 2 or x == 3
or x in {1, 2, 3}
.
Check if multiple variables have the same value
If you have an arbitrary sequence, use the all()
function with a generator expression:
values = [x, y, z] # can contain any number of values
if all(v == 1 for v in values):
otherwise, just use ==
on all three variables:
if x == y == z == 1:
If you only needed to know if they are all the same value (regardless of what value that is), use:
if all(v == values[0] for v in values):
or
if x == y == z:
Query with where clause checking a variable with multiple values
It is not possible to define a list as a variable. You would have to declare your variable as a temporary table.
In your use case, you seem to be looking for dynamic sql.
declare @myList varchar(100)
set @myList = '( "Owner", "Admin", "Rule" )'
exec('SELECT * FROM product.text_data WHERE product.text_data.field_ref IN' + @myList)
Why does checking a variable against multiple values with `OR` only check the first value?
("Jesse" or "jesse")
The above expression tests whether or not "Jesse"
evaluates to True
. If it does, then the expression will return it; otherwise, it will return "jesse"
. The expression is equivalent to writing:
"Jesse" if "Jesse" else "jesse"
Because "Jesse"
is a non-empty string though, it will always evaluate to True
and thus be returned:
>>> bool("Jesse") # Non-empty strings evaluate to True in Python
True
>>> bool("") # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>
This means that the expression:
name == ("Jesse" or "jesse")
is basically equivalent to writing this:
name == "Jesse"
In order to fix your problem, you can use the in
operator:
# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):
Or, you can lowercase the value of name
with str.lower
and then compare it to "jesse"
directly:
# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":
Typescript If statement with multiple value matches for the same variable
Syntactically, you can use switch
instead of if
to test for multiple values using repeating cases:
switch (x) {
case 5:
case "":
case undefined:
// do something
break;
}
But this is rarely done.
To programatically test for multiple values, you can put the values in an array and check that it includes your argument value using indexOf
:
if ([5, "", undefined].indexOf(x) >= 0) {
...
}
Note that this will create the values array each time, so if this check repeats you might want to create the array once, elsewhere, and reuse it.
const values = [5, "", undefined];
// elsewhere
if (values.indexOf(x) >= 0) {
...
}
In fact, if the number of values to test is large, you might want to put them in a Set
and check that it has
them, as this is faster than testing against an array:
const values = new Set(5, "", undefined);
// elsewhere
if (values.has(x)) {
...
}
Related Topics
How to Use Xpath with Beautifulsoup
Why Do You Need Explicitly Have the "Self" Argument in a Python Method
Method Resolution Order (Mro) in New-Style Classes
Keep Only Date Part When Using Pandas.To_Datetime
Getting Distance Between Two Points Based on Latitude/Longitude
How to Access the Ith Column of a Numpy Multidimensional Array
How to Split a String of Space Separated Numbers into Integers
Pandas: Multiple Conditions While Indexing Data Frame - Unexpected Behavior
Strings in a Dataframe, But Dtype Is Object
How to Remove a Substring from the End of a String
How to Efficiently Parse Fixed Width Files
How to Get Monitor Resolution in Python
Unicodedecodeerror: 'Utf8' Codec Can't Decode Byte 0Xa5 in Position 0: Invalid Start Byte
Should You Always Favor Xrange() Over Range()
Update Value of a Nested Dictionary of Varying Depth
How to Test That a Python Function Throws an Exception
Convert Python Sequence to Numpy Array, Filling Missing Values