[Tutor] if n == 0 vs if not n
wescpy at gmail.com
Mon Oct 5 21:52:20 CEST 2009
> I am going through someone's python script and I am seeing a lot of the
> following boolean checks.
> if not s == ""
> if not n == 0
> if b == True
> if not b == True
> All of these can be written without the == notation like "if n", "if s"
> etc.Now in this case where it is only used as boolean checks which would be
> the most pythonic way if writing these checks?
it would be the same as what you have already described. checking
against Boolean literals follows the same logic, i.e., "if b", "if not
b", etc. of course, the reasoning behind what you said and my
suggestion is that all Python objects evaluate to some sort of Boolean
value. the "== 0" and '== ""' (and their corresponding "not"s) aren't
necessary because both 0 and "" have a Boolean False value, as does
the general rule is that any numeric zero (0, 0.0, 0.0+0.0J, etc.) or
empty "container" (i.e., str, list, tuple, dict, set, etc.), are all
False. all other values are True.
hope this helps!
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
More information about the Tutor