Question

I'm relatively new to Python and Coding. I've been doing fine until I've come across "None":

variable = None                          
while variable != "":                    
    print("Why does this loop start?")

While it seems simple I can't grasp why the above loop begins. How is None different to an empty string? I thought they both evaluated to False.

Was it helpful?

Solution

They both evaluate to False but that doesn't mean they're the same thing.

None is a separate value and it has its own type. An empty string is a string without contents:

>>> type(None)
<type 'NoneType'>
>>> type('')
<type 'str'>
>>> bool(None) == bool('')
True
>>> None == ''
False

OTHER TIPS

No, None is only the same thing as None itself. Empty strings are not the same thing:

>>> None == ""
False

None is a special singleton value (there is only one copy of it in a Python session) signifying 'emptyness', or the lack of a 'proper' value. As such it is a flag or signal value; Python uses it by convention to signal that a process didn't return anything, for example.

Both None and the empty string are considered false in a boolean context:

>>> bool(None)
False
>>> bool("")
False

as are all empty containers (such as an empty tuple, list or set) and numeric 0 (be it integer, floating point or a complex number). Being considered false doesn't make them equal, however.

If you wanted to test for any value that is false, use:

while not variable:

as not interprets the operand in a boolean context and returns the inverse value:

>>> not ""
True
>>> not None
True
>>> not "not empty"
False

They both evaluate to False, but are different when used in a comparison

if not None:
    print "Always true"
if not "":
    print "Always true"
if bool(None) == bool(""):
    print "Always true"
if None == "":
    pass
    #always false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top