None
None is a special value that represents the absence of a value.
Syntax
result = NoneNone is Python's way of saying "no value" or "nothing here yet". It is its own type, called NoneType, and there is only ever one None.
Where you see it
- As a default for a variable that has no meaningful value yet.
- As the return value of a function that does not explicitly return anything.
Check for it with is, not ==: write if x is None.
Example
result = None
print(result)
print(result is None)
def do_nothing():
pass
print(do_nothing())
# Output:
# None
# True
# NoneWhen to use it
- A search function returns None when the item is not found, letting callers detect 'no result'.
- A database record uses None for optional fields like middle_name that may not exist.
- A function with no explicit return statement implicitly returns None, which the caller checks.
More examples
None as a default placeholder
Assigns None as an initial placeholder and checks it with the identity operator 'is'.
result = None
print(result) # None
print(result is None) # TrueFunction returning None
Returns None when a search fails so callers can distinguish 'found' from 'not found'.
def find_user(users, name):
for user in users:
if user == name:
return user
return None
found = find_user(['Alice', 'Bob'], 'Carol')
if found is None:
print('User not found')
# Output:
# User not foundNone vs falsy values
Contrasts 'is None' (identity) with 'not value' (falsy) to show when each is appropriate.
a = None
b = 0
c = ''
print(a is None) # True
print(b is None) # False
print(not a, not b, not c) # True True True
Discussion