What is this “and” statement actually doing in the return?

前端 未结 3 585
暖寄归人
暖寄归人 2020-12-20 14:16

I am trying to get a better understanding of the following python code and why the author has used the \"AND\" statement in the return.

def valid_password(se         


        
3条回答
  •  伪装坚强ぢ
    2020-12-20 15:09

    In Python, both and and or will return one of their operands. With or, Python checks the first operand and, if it is a "truthy" value (more on truthiness later), it returns the first value without checking the second (this is called Boolean shortcut evaluation, and it can be important). If the first is "falsey", then Python returns the second operand, no matter what it is:

    Python 2.7.3 (default, Jan  2 2013, 13:56:14)
    [GCC 4.7.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 2 or 3
    2
    >>> 0 or 3
    3
    

    With "and", much the same thing happens: the first operand is checked first, and if it is "falsey", then Python never checks the second operand. If the first operand is "truthy", then Python returns the second operand, no matter what it is:

    >>> 2 and 3
    3
    >>> 0 and 3
    0
    >>> 3 and 0
    0
    >>> 3 and []
    []
    >>> 0 and []
    0
    

    Now let's talk about "truthiness" and "falsiness". Python uses the following rules for evaluating things in a Boolean context:

    • The following values are "falsey": False, None, 0 (zero), [] (the empty list), () (the empty tuple), {} (the empty dict), an empty set, "" (the empty string)
    • Everything else is "truthy"

    So something like password and PASS_RE.match(password) is taking advantage of Python's short-circuit evaluation. If password is None, then the and operator will just return None and never evaluate the second half. Which is good, because PASS_RE.match(None) would have thrown an exception. Watch this:

    >>> 3 or []
    3
    >>> [] or 3
    3
    >>> 0 or []
    []
    >>> [] or 0
    0
    >>> 0 and []
    0
    >>> [] and 0
    []
    

    See how the short-circuiting is working? Now watch this:

    >>> value = "hello"
    >>> print (value.upper())
    HELLO
    >>> print (value and value.upper())
    HELLO
    >>> value = None
    >>> print (value.upper())
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'NoneType' object has no attribute 'upper'
    >>> print (value and value.upper())
    None
    

    See how the short-circuiting feature of and helped us avoid a traceback? That's what's going on in this function.

提交回复
热议问题