Practical Python AND Examples

Python has a Truth Check feature for all objects. What allows Boolean Operators a more general definition that is suitable for all objects:

  • x or y : if x is false, then y, else x
  • x and y : if x is false, then x, else y

I saw practical use cases for an OR operator, for example:

 ENV_VAR = os.environ.get('ENV_VAR') or <default_value> 

However, I have not seen a practical example of using the Python AND operator. Here I am looking for examples of an AND operator that uses truth testing, for example, the example of the OR operator above.

+1
python boolean
Feb 26 '16 at 16:37
source share
5 answers

The most common use of and in python is simply checking for several conditions:

 if 13 <= age <= 19 and gender == 'female': print "it a teenage girl" 

Use cases for and that take advantage of the unexpectedly unexpected fact that x and y returns one of the operands rather than returning a boolean, a little and far between. There is almost always a clearer and more readable way to implement the same logic.

In earlier python code, you can often find the construct below, which is an unsuccessful attempt to replicate the behavior of a C-ternary C operator ( cond ? : x : y ).

 cond and x or y 

It has a drawback: if x is 0 , None , '' or any false, then y will be chosen instead, so it is not quite equivalent to version C,

The following is the โ€œfixedโ€ version:

 (cond and [x] or [y])[0] 

These types and / or hacks are mostly deprecated since python introduced a conditional expression .

 x if cond else y 
+1
Feb 26 '16 at 17:07
source share

Function used in your example

 os.environ.get('ENV_VAR') or <default_value> 

called short circuit assessment . If this aspect of AND and OR is the subject of your question, you may find this Wikipedia article useful:

https://en.wikipedia.org/wiki/Short-circuit_evaluation

0
Feb 26 '16 at 17:21
source share

In this answer, I found some great examples for the and and or operators: https://stackoverflow.com/a/166778/

Direct quote from the answer:

The Python or operator returns the first value of Truth-y or the last value and stops. This is very useful for programming utilities that require fallback values.

Like this simple one:

 print my_list or "no values" 

...

A compliment with and , which returns the first False-y value or the last value and stops, is used when protection is required, not reserve.

Like this:

 my_list and my_list.pop() 
0
Feb 26 '16 at 21:47
source share

I sometimes use and when I need to get an attribute of an object if it is not None , otherwise get None :

 >>> import re >>> match = re.search(r'\w(\d+)', 'test123') >>> number = match and match.group(1) >>> number >>> '123' >>> match = re.search(r'\w(\d+)', 'test') >>> number = match and match.group(1) >>> number 
0
Feb 26 '16 at 21:58
source share

Whenever you need an expression in which two things must be true. For example:

 # you want to see only odd numbers that are in both lists list1 = [1,5,7,6,4,9,13,519231] list2 = [55,9,3,20,18,7,519231] oddNumsInBothLists = [element for element in set(list1) if element in set(list2) and element % 2] # => oddNumsInBothLists = [7, 9, 519231] 

Boolean operators, in particular, and, can usually be omitted due to readability. The built-in function all() will return true if and only if all its members are true. Similarly, the any() function will return true if any of its members is true.

 shouldBeTrue = [foo() for foo in listOfFunctions] if all(shouldBeTrue): print("Success") else: print("Fail") 

Perhaps an easier way to think that or will be used instead of consecutive if statements, while and will be used instead of nested if statements.

 def foobar(foo, bar): if(foo): return foo if(bar): return bar return False 

functionally identical:

 def foobar(foo, bar): return foo or bar 

and

 def foobar(foo, bar): if(foo): if(bar): return bar return False 

functionally identical:

 def foobar(foo, bar): return foo and bar 

This can be demonstrated with a simple test.

 class Foo: def __init__(self, name): self.name = name test1 = Foo("foo") test2 = Foo("bar") print((test1 or test2).name) # => foo print((test1 and test2).name) # => bar print((not test1 and not test2).name) # => AttributeError for 'bool' (False) 
-one
Feb 26 '16 at 17:01
source share



All Articles