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

前端 未结 3 584
暖寄归人
暖寄归人 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 14:54

    You just need to know that:

    1. Empty strings in Python evaluates to False (also None, empty lists, and other "zero" types).
    2. Boolean expressions are subject to an optimization called short-circuit evaluation

    Therefore,

    a = '1'
    print('' and a)
    

    ... prints the empty string because as it is False, the expression can never be True and the second part (the a) is never even evaluated.

    And

    a = '1'
    print('' or a)
    

    prints '1', because the empty string is False, the second part has to be evaluated to give the result of the expression.

提交回复
热议问题