Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operator "and" in python

Tags:

python

Why is the self.year twice? I am having trouble to find out the logic of the line. Can some one help me with this?

return (self.year and self.year == date.year or True)

I am going through http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html and encountered the line ... And of course I have no problem understanding and, or, nor, xor, xnor, or any boolean expression. But I am confused by the way it has been used here..

:-)

like image 276
Nabin Avatar asked Nov 26 '25 12:11

Nabin


2 Answers

The order of evaluation matters (see here). The code:

return self.year and self.year == date.year

could be rewritten:

return self.year and (self.year == date.year)

Or, in full:

if self.year:
    if self.year == date.year:
        return True
    else:
        return False
return False # Actually return self.year, but usually a boolean is intended in this sort of situation

However, the expression you posted will always evaluate to True because of the or True at the end. Using parenthesis to show evaluation order:

return (self.year and (self.year == date.year)) or True
like image 130
aquavitae Avatar answered Nov 29 '25 02:11

aquavitae


This line will always return true because you are doing an or with a true value.

Apart from that, first it checks if self.year is not None or False, than checks if self.year is equal to date.year.

like image 36
fede1024 Avatar answered Nov 29 '25 01:11

fede1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!