None is a special keyword that represents the absence of a value. It is commonly used to indicate that a variable has no value assigned or that a function does not return anything explicitly.
def show():
pass
print(show())
Output
None
Explanation: show() does not contain a return statement so, Python automatically returns None.
Common Uses of None
- Initializing variables: Assign None when a variable is created but its actual value will be assigned later.
- Representing missing data: Use None to indicate that a value is currently unavailable or does not exist.
- Default function arguments: Set parameters to None when an argument is optional and a value may or may not be provided.
- Indicating no return value: Functions that do not explicitly return a value automatically return None.
None vs Other Empty Values
Although None, False, 0 and "" may all behave as false values in conditions, they represent different things in Python.
print(None == False)
print(None == 0)
print(None == "")
Output
False False False
Explanation:
- None represents the absence of a value and False represents a boolean false value.
- 0 represents the numeric value zero and "" represents an empty string.
Examples
Example 1: The following example assigns None to a variable. This is often used to indicate that a variable currently has no value.
x = None
print(x)
print(type(x))
Output
None <class 'NoneType'>
Explanation: x = None assigns the special value None to x and type(x) returns NoneType, which is the data type of None.
Example 2: The following example checks whether a variable contains None using the is operator.
x = None
if x is None:
print("No value assigned")
else:
print("Value exists")
Output
No value assigned
Explanation:
- is None is the recommended way to check whether a variable contains None.
- Since x is None, the condition evaluates to True.
Example 3: The following example uses None as a default parameter value when no argument is provided.
def greet(name=None):
if name is None:
print("Hello, Guest")
else:
print("Hello,", name)
greet()
greet("Emma")
Output
Hello, Guest Hello, Emma
Explanation:
- name=None sets None as the default value.
- When no argument is passed, name remains None and the default message is displayed.