Lessons · Python · checking for None
Nothing is a value too
None means 'no value'. Check for it with 'is None', and check it before you use the thing.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
A missing lookup, an optional field, a function that returned nothing: None arrives constantly. Using it as if it were a value is the 'NoneType has no attribute' error you will meet weekly.
How to think about it
Where can None come from here? Ask where None can come from: dict.get, a function with no return, an optional parameter. Test 'if x is None' at the boundary, and decide what the fallback is.
Worked example
user = find_user("ada")Might return None if not found.if user is None:'is', not '=='. None is a single object.
print("no such user")Handle the absence.else:The other branch: we have a real user.
print(user.email)Safe now.
Your turn
Fall back to 'guest' when name is None.
label = name if name None else "guest"
Solve one with the tests running
The trap
Using 'if x:' to test for None. 0, empty string and empty list are also falsy, so a real value of 0 gets treated as missing.