What does this “if” statement mean?

Deadly 提交于 2019-12-24 10:46:44

问题


In an example Hadoop reduce program, such an "if" statement exists. I am wondering what it means when the same variable "a" is used twice in the "if" statement, as follows

if a and a == b:
    print "It is working!"

回答1:


It will test for equality (a == b) only if a is truthy.

It can be rewritten as

if a:
    if a == b:
        print("It is working!")

Note the operator precedence: it's not equal to if (a and a) == b.




回答2:


There's no real magic here.

And and expression is truthy iff both sides are truthy.

a is truthy iff it's not False, None, a numeric 0, or an empty collection.

a == b is truthy iff a and b are equal (in some sense appropriate to their type).

So, for example, if a and b can be either a list or None, this will be true if a is a non-empty list and b is a non-empty list with the same values.



来源:https://stackoverflow.com/questions/25629857/what-does-this-if-statement-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!