None and defaults in Python
Representing absence: the value that means nothing was found.
def find_user(users, name):
for user in users:
if user["name"] == name:
return user
return None
user = find_user([{"name": "sam"}], "alex")
if user is None:
display = "guest"
else:
display = user["name"]
nickname = None
shown = nickname or "anonymous"
How it works
- A search that finds nothing returns
Noneexplicitly. - Checks identity with
is None, never== None. - Falls back to a default with the
oridiom.
Keywords and builtins used here
defelsefind_userforifreturn
The run, in numbers
- Lines
- 15
- Characters to type
- 254
- Tokens
- 77
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 54 seconds.
Step 5 of 6 in Variables & types, step 5 of 72 in Language basics.