问题
if not start:
new.next = None
return new
what does "if not" mean? when will this code execute?
is it the same thing as saying if start == None: then do something?
回答1:
if
is the statement. not start
is the expression, with not
being a boolean operator.
not
returns True
if the operand (start
here) is considered false. Python considers all objects to be true, unless they are numeric zero, or an empty container, or the None
object or the boolean False
value. not
returns False
if start
is a true value. See the Truth Value Testing section in the documentation.
So if start
is None
, then indeed not start
will be true. start
can also be 0
, or an empty list, string, tuple dictionary, or set. Many custom types can also specify they are equal to numeric 0 or should be considered empty:
>>> not None
True
>>> not ''
True
>>> not {}
True
>>> not []
True
>>> not 0
True
Note: because None
is a singleton (there is only ever one copy of that object in a Python process), you should always test for it using is
or is not
. If you strictly want to test tat start
is None
, then use:
if start is None:
回答2:
It executes when start
is False
, 0
, None
, an empty list []
, an empty dictionary {}
, an empty set...
来源:https://stackoverflow.com/questions/34376441/if-not-condition-statement-in-python