None
None is Python's special value for "there is nothing here", and you check it with `is None`.
Used in 85 lessons of the course, from 00.02.
None is a single value that stands for the absence of a value. It is not 0, not "", and not False: it is its own thing, and its type is NoneType.
You will meet None in three places:
- As a starting value: "I don't have anything yet".
- As a parameter default:
def f(path=None). - As the result of a function with no
return.
To ask whether something is None, use is None, not == None. There is only one None in the whole program, so is (identity) asks the exact question and doesn't depend on how an object defines ==.
if path is None:
path = "default.txt"
In the course, if path is None: shows up from lesson 00.02: it means "if the caller gave me no path, I use my own".
Reach for it when: you need to represent "no value yet" or "not provided", and always compare it with `is None`.
Examples
Common mistake
def add_tax(price):
price * 1.2
total = add_tax(100)
print(total + 1)Why: The function computes the value but never returns it, so `total` is `None` and you can't add 1 to it.
How to write it: Write return price * 1.2.
Common mistake
def label(count=None):
if count is None:
return "empty"
return "has items"
print(label(0))Why: Using `if not count:` would mix up `0` and `None`. Here `is None` tells them apart: 0 is a value that was given.
How to write it: Use is None when you only want to detect absence, and not when you also want 0 or empty to count as "nothing".
