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?
Using the 'if not' Python statement to check if it negates the output of an 'if' statement. As you can see, the code under the 'if' block was returned although the condition returned false. This is because the 'not' operator negated its value.
Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn't true, there's another one that you want to test. Then, if neither is true, you want the program to do something else. There's no good way to do that using just if and else .
The != operator compares the value or equality of two objects, whereas the Python is not operator checks whether two variables point to the same object in memory.
Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With