Python for Programmers: None
Welcome to the None lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Noneis Python's null value, used to indicate the lack of something. It's similar to thenullornilvalues in many other languages, orundefinedin JavaScript.We use
value is Noneto decide whether a value isNone. It returns a boolean.>
None is NoneResult:
True
>
"something" is NoneResult:
False
>
address = Noneif address is None:message = "no address"else:message = "the address is " + addressmessageResult:
'no address'
This works because there's only one
Nonevalue. No matter where we refer toNone, we get exactly the same value, stored at the same place in memory.It's also possible to check with
value == None, but that's considered bad style.>
# This isn't recommended! Use `is` instead.None == NoneResult:
True
As we saw in an earlier lesson on identity, we can also use the
is notcomparison to ask "are these two different values, stored at different locations in memory?" This is especially common when comparing againstNone.value is not Nonegives us the same result asnot (value is None). However,value is not Noneis generally considered more readable.>
not (3 is None)Result:
True
>
3 is not NoneResult:
True
Functions that lack a
returnstatement automatically returnNone. (They have to return something!) An unexpectedNoneoften means that we forgot thereturnstatement.>
def double(x):2 * xdouble(2)Result:
None
One final note about
None. If you're familiar with JavaScript, note that Python doesn't share JavaScript's distinction betweennullandundefined. Like most languages, Python only has one "null" or "empty" value:None.