What is None in Python and how is it different from 0, False or an empty string?
None is a special singleton object of type NoneType that means no value. It is falsy like 0, False and '', but it is not equal to any of them. Functions without a return statement return None, and you should test for it with is None.
Explain it simply
Picture an exam result sheet. A score of 0 means the student wrote the paper and scored nothing. A blank cell means the result has not come in yet. 0 is the first case; None is the blank cell. Both look "empty" in an if statement, but they mean very different things.
Example
def find_roll_number(name, records):
for roll, student in records.items():
if student == name:
return roll
# no return here, so the function returns None
records = {0: "Asha", 1: "Ravi"}
roll = find_roll_number("Asha", records)
if not roll:
print("not found") # wrong! prints, because roll 0 is falsy
if roll is None:
print("not found")
else:
print("roll", roll) # roll 0
print(None == 0, None == False, None == "") # False False False
print(type(None)) # <class 'NoneType'>The first check is a real bug: a valid roll number of 0 is treated as "missing".
What to say in the interview
"None is Python's single 'no value' object. It is falsy, but it is not equal to 0, False or ''. Functions return it implicitly, and optional parameters often default to it. I test with is None because there is only one None, and so that a valid 0 or empty string is not mistaken for 'missing'."
Common mistakes
- Using
if not x:when0or""are valid values. - Using
== None, which a class can override through__eq__.