And or with values in a list : And Or « Language Basics « Python






And or with values in a list

And or with values in a list
t, f = 1, 0
x, y = 88, 99

a = (t and x) or y           # if true, x
print a

a = (f and x) or y           # if false, y
print a


print ((t and [x]) or [y])[0]     # if true, x

print ((f and [x]) or [y])[0]     # if false, y

print (t and f) or y              # fails: f is false, skipped

print ((t and [f]) or [y])[0]     # works: f returned anyhow


           
       








Related examples in the same category

1.Introducing andIntroducing and
2.And Or in Python: int, empty list and empty dictionaryAnd Or in Python: int, empty list and empty dictionary
3.Introducing orIntroducing or
4.Using the and-or TrickUsing the and-or Trick
5.When the and-or Trick FailsWhen the and-or Trick Fails
6.Using the and-or Trick Safely