Skip to content Skip to sidebar Skip to footer

Practical Examples Of Python And Operator

Python has the Truth Value Testing feature for all the objects. Which enables the Boolean Operators a more generic definition that suits for all objects: x or y: if x is false, th

Solution 1:

By far the most common use of and in python is just to check multiple conditions:

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

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

In older python code, you can often find the construct below, which is a buggy attempt to replicate the behaviour of C's ternary operator (cond ? : x : y).

cond and x or y

It has a flaw: if x is 0, None, '', or any kind of falsey value then y would be selected instead, so it is not quite equivalent to the C version.

Below is a "fixed" version:

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

These kind of and/or hacks are mostly obsolete now since python introduced the conditional expression.

x if cond else y

Solution 2:

The feature used in your example

os.environ.get(‘ENV_VAR’) or <default_value>

is called short circuit evaluation. 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

Solution 3:

I found great examples for both and and or operator in this answer: https://stackoverflow.com/a/28321263/5050657

Direct quote from the answer:

Python's or operator returns the first Truth-y value, or the last value, and stops. This is very useful for common programming assignments that need fallback values.

Like this simple one:

print my_list or "no values"

...

The compliment by using and, which returns the first False-y value, or the last value, and stops, is used when you want a guard rather than a fallback.

Like this one:

my_list and my_list.pop()

Solution 4:

I am sometimes using and when I need to get an attribute of an object if it's 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

Solution 5:

Any time you need a statement where two things should be true. For example:

# you want to see only odd numbers that are in both listslist1 = [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, particularly the and, can generally be omitted at the expense of readability. The builtin function all() will return true if, and only if, all of its members are true. Similarly, the function any() will return true if any of its members are true.

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

Perhaps an easier way of thinking about it is that or would be used in place of successive if-statements whereas and would be used in place of nested if-statements.

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

is functionally identical to:

deffoobar(foo, bar):
    return foo or bar

And:

deffoobar(foo, bar):
    if(foo):
        if(bar):
            return bar
    returnFalse

is functionally identical to:

deffoobar(foo, bar):
    return foo and bar

This can be demonstrated with a simple test.

classFoo:
    def__init__(self, name):
        self.name = name

test1 = Foo("foo")
test2 = Foo("bar")

print((test1 or test2).name) # => fooprint((test1 and test2).name) # => barprint((not test1 andnot test2).name) # => AttributeError for 'bool' (False)

Post a Comment for "Practical Examples Of Python And Operator"