Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"If not" condition statement in python [duplicate]

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?

like image 817
kaka Avatar asked Dec 19 '15 23:12

kaka


People also ask

How do you write if not condition in Python?

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.

Can an if statement have multiple conditions Python?

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 .

Is not VS != In Python?

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.

Is not none condition in Python?

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).


1 Answers

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:
like image 137
Martijn Pieters Avatar answered Nov 15 '22 18:11

Martijn Pieters