doc doc - 1 year ago 62
Python Question

Several variables in if-statement

This works as intended:

if c1 in r':6' or c2 in r':6':
subst_weight = 1

This doesn't:

if (c1 or c2) in r':6':
subst_weight = 1

Why and what is the differnce? The goal is to find out whether
is in the string.
Same here:


if c1 == '6' or c2 == '6':

Doesn't work:

if (c1 or c2) == '6':


Answer Source

The statement one or two will return one if defined, and two if one is not truthy, and I don't see a reason it wouldn't work with your logic because if either is truthy, and is contained in string, it will evaluate to True

>>> a = "6"
>>> b = ":"
>>> (a or b)
>>> (b or a)
>>> a = None
>>> (a or b)
>>> b

For more than 2 variables it will return the first that's truthy

>>> a = None
>>> b = None
>>> c = 6
>>> a or b or c

But note your logic, you want to check if any of the variables is in that string, you can't use this, because the c1 ca be equal to "adasd" and that's what's gonna be returned to that if statement and it's not in ":6"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download