Execute Program

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!

  • None is Python's null value, used to indicate the lack of something. It's similar to the null or nil values in many other languages, or undefined in JavaScript.

  • We use value is None to decide whether a value is None. It returns a boolean.

  • >
    None is None
    Result:
    TruePass Icon
  • >
    "something" is None
    Result:
    FalsePass Icon
  • >
    address = None
    if address is None:
    message = "no address"
    else:
    message = "the address is " + address
    message
    Result:
    'no address'Pass Icon
  • This works because there's only one None value. No matter where we refer to None, 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 == None
    Result:
    TruePass Icon
  • As we saw in an earlier lesson on identity, we can also use the is not comparison to ask "are these two different values, stored at different locations in memory?" This is especially common when comparing against None. value is not None gives us the same result as not (value is None). However, value is not None is generally considered more readable.

  • >
    not (3 is None)
    Result:
    TruePass Icon
  • >
    3 is not None
    Result:
    TruePass Icon
  • Functions that lack a return statement automatically return None. (They have to return something!) An unexpected None often means that we forgot the return statement.

  • >
    def double(x):
    2 * x

    double(2)
    Result:
    NonePass Icon
  • One final note about None. If you're familiar with JavaScript, note that Python doesn't share JavaScript's distinction between null and undefined. Like most languages, Python only has one "null" or "empty" value: None.