Если видео недоступно для просмотра, попробуйте выключить блокировщик рекламы.

###Logical expressions in Python

Logical expressions

  • occur when use compare or boolean operators
  • >, <, ==, is, in, and, or, not
  • are used in if operator
  • return boolean values

Examples

if value > 10:
    # ...
if status == 'active':
    # ...
if user.age > 16 and not user.is_banned:
    # ....

Boolean operators

  • AND (binary) — true if both operands are true
  • OR (binary) — true if at least one of operands is true
  • NOT (unary) — reverse

NOT has higher priority than AND and OR

Examples

10 > 2 and 10 > 9         # True
10 > 2 and 10 > 11        # False
10 > 2 or 10 > 11         # True
10 > 2 and not 10 > 11    # True
not (10 > 2 or 10 > 11)   # False

Any object behaves like bool

# False
None    ''    u""    0    0.0     {}     ()     []    set()

# True
- non-empty string or collection
- non-zero number

bool(0)           # False
bool([])          # False
bool('')          # False
bool({})          # False
bool(0.00001)     # True
bool(-1)          # True
bool(' ')         # True
bool(' '.strip()) # False
bool((0, 0, ))    # True
bool(None)        # False

result = 0
if result:
    # no code
else:
    print "result is zero"

data = {}
if data:
   # no code
else:
   # code goes there

How to override bool behaviour

  • Override __nonzero__ method in Py2
  • __bool__ in Py3

How to override bool behaviour

# rarely
class Balance(int):
    def __nonzero__(self):
        return self > 0

balance = Balance(-10)
if balance: # False

# common
class User(object):
    def is_balance_ok(self):
        return self.balance > 0

user = User(balance=-10)
if user.is_balance_ok(): # False

Expressions return values

# Some languages
if (balance > 0) {
    can_pay = True;
} else {
    can_pay = False;
}

# Python
can_pay = balance > 0
can_pay = user.balance > 0 and not user.is_banned
can_pay = (
    user.balance > 0
    and not user.is_banned
    and user.has_perm('buy')
)
is_active = status not in ('banned', 'pending')
can_exit = user.age > 18 and is_confirmed
ok = 'error' not in response['text']
ok = error is None

Is value None?

# bad
val == None
type(None) == types.NoneType

# OK
value is None
value is not None

Ternary operator

var x = (a > b) ? a : b; // javascript
x = (...) if (...) else (...)
x = a if a > b else b
res = (process_good_result(data)
       if data else process_bad_result(data))

Boolean expressions are lazy

def func(x):
    print x
    return bool(x)

res = func(1) and func(0) and func(2) and func(3)    # False
>>> 1 0
res func(1) and func(3) and func(2) and func(0)      # False
>>> 1 3 2 0

res = func(1) or func(2)       # True
>>> 1
res = func(0) or func(1) or func(2) or func(3) # True
>>> 0 1

So put the easiest expressions in OR at the first place.

Conclusion

  • occur when use compare or logical operators
  • return boolean value
  • any object can be used as a predicate
  • value is None, but not value == None
  • use ternary operator
  • remember about laziness
Мы учим программированию с нуля до стажировки и работы. Попробуйте наш бесплатный курс «Введение в программирование» или полные программы обучения по Node, PHP, Python и Java.

Хекслет

Подробнее о том, почему наше обучение работает →