typestar

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

  1. A search that finds nothing returns None explicitly.
  2. Checks identity with is None, never == None.
  3. Falls back to a default with the or idiom.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 6 in Variables & types, step 5 of 72 in Language basics.

← Previous Next →