I’m a new member here and also new to python. My question is as follows, is it valid to have a line like this?
if x or y is 'whatever':
I tested this in the interpreter and am getting inconsistent results. It would seem that this line yields more consistent and expected results
if (x or y) is 'whatever':
Or is it always best to explicitly have everything laid out as such
if x is 'whatever' or y is 'whatever':
This last one always works but I’m just trying to make my code a bit more concise while still following best practices. I tried doing a search so as not to ask a redundant question but searching for ‘is’ ‘or’ and ‘and’ is rather difficult. Thanks in advance for any assistance.
edit: Thanks all for the quick replies. This works perfectly for me when I need ‘or’
if 'whatever' in [x,y]:
But how would I condense this if I need an ‘and’?
if x == 'whatever' and y == 'whatever':
ordoesn’t work like it does in English.x or yreturns x if x is a true-ish value, otherwise it returns y. Strings are true-ish if they are not empty.Worse, “is” has a higher precedence that “or”, so your expression is the same as
x or (y is 'whatever'). So if x is not empty, it returns x (which will be true, so the if will execute). If x is empty, it will evaluatey is 'whatever'.BTW: Don’t use “is” to compare value equality, use ==.
You want this (parens optional):
or more concise, but stranger: