Question
How do I represent or refer to a null value in Python?
Short Answer
Python does not use a keyword named null. Instead, it uses the singleton object None to represent the absence of a value. You will learn how to assign, test, and use None safely in Python programs.
Concept
Python's equivalent of a null value is None.
result = None
None is a special built-in object that means no value is present, a value is unknown, or an operation has no meaningful result. Its type is NoneType.
print(type(None)) # <class 'NoneType'>
There is only one None object in a Python program. This is why Python code tests for it with identity operators:
if result is None:
print("No result is available")
None matters because many functions, APIs, and optional variables need a clear way to distinguish “there is no value” from values such as 0, "", or False.
Mental Model
Think of a variable as a labeled box.
score = 0means the box contains the number zero.name = ""means the box contains an empty piece of text.active = Falsemeans the box contains a false value.email = Nonemeans the box currently has no email value at all.
None is not an empty string, zero, or False. It is a specific marker that says, “there is nothing here yet.”
Syntax and Examples
Use None with a capital N and lowercase one.
user_address = None
Test whether a value is None with is or is not:
user_address = None
if user_address is None:
print("Address has not been provided.")
else:
print(user_address)
Use is not None when a value must be present before you use it:
age = 21
if age is not None:
print(f"Age: {age}")
Many Python functions return None when they perform an action instead of calculating and returning a new value:
Step by Step Execution
Consider this example:
def find_discount(code):
discounts = {"SAVE10": 10, "SAVE20": 20}
return discounts.get(code)
amount = find_discount("WELCOME")
if amount is None:
print("Discount code was not found.")
else:
print(f"Discount: {amount}%")
Step by step:
find_discount("WELCOME")runs.- The dictionary contains
SAVE10andSAVE20, but notWELCOME. dict.get()returnsNonewhen a key is missing and no fallback value was provided.amountis assignedNone.amount is Noneevaluates toTrue.- The program prints
Real World Use Cases
None is common whenever data may be optional or unavailable.
- Database records: A user may not have supplied a phone number yet.
phone_number = None - API data: A response may omit an optional field such as a profile image.
avatar_url = response.get("avatar_url") - Search functions: A function may return
Nonewhen it cannot find an item.product = find_product(product_id) - Optional function arguments:
Nonecan mean “use the default behavior.”def connect(timeout=None): if timeout is None: timeout = 30 - In-place operations: Methods such as
list.sort()andlist.append()returnNonebecause they modify an existing object.
Real Codebase Usage
In real projects, developers use None to model optional values and to make decisions before using data.
Guard clauses
Return early when a required value is missing:
def send_receipt(email):
if email is None:
return False
print(f"Sending receipt to {email}")
return True
Validation
Check that required input was provided:
def create_account(username, password):
if username is None or password is None:
raise ValueError("Username and password are required")
Defaults without overwriting valid false-like values
Use an explicit None check when 0, False, or an empty string are valid inputs:
Common Mistakes
Writing null, NULL, or none
Python is case-sensitive and has no null keyword.
# Broken: NameError
value = null
Use None:
value = None
Comparing with == None
This often works, but is None is the recommended and clearest form. Equality can be customized by objects, while identity checks whether the value is the actual singleton None.
# Avoid
if value == None:
pass
# Prefer
if value is None:
pass
Treating None as the same as False, , or
Comparisons
| Value | Meaning | Example use |
|---|---|---|
None | No value / value absent | An optional database field was not supplied |
False | A boolean negative result | A user is not signed in |
0 | Numeric zero | A cart contains zero items |
"" | Empty text | A user submitted an empty comment |
[] | Empty list | A search found no matching records |
is versus ==
Cheat Sheet
# Represent no value
value = None
# Preferred checks
if value is None:
pass
if value is not None:
pass
# Optional argument pattern
def greet(name=None):
if name is None:
name = "Guest"
return f"Hello, {name}!"
# Safe mutable default pattern
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
- Python uses
None, notnull. Nonehas typeNoneType.- There is only one
Noneobject. - Prefer and .
FAQ
Is None the same as null in Python?
Conceptually, yes: None is Python's standard value for representing no value. Python does not have a null keyword.
Why should I use is None instead of == None?
None is a single shared object. is None directly checks for that object and is the standard Python style.
Is None false in an if statement?
Yes, None is false-like, so if None: does not run. However, it is distinct from False, 0, and empty collections.
Can a function return None?
Yes. A function with no return statement returns None automatically. Functions may also explicitly use return None.
Mini Project
Description
Build a small profile formatter that accepts optional user details. It demonstrates how None represents missing information and how explicit is None checks preserve valid values such as 0.
Goal
Create a function that displays a user profile while replacing missing values with helpful defaults.
Requirements
- Create a function named
format_profilethat acceptsname,age, andcity. - Treat
nameandcityas optional values. - Display
"Anonymous"whennameisNone. - Display
"Unknown"whencityisNone. - Preserve an age of
0rather than treating it as missing.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.