Home »
Python
Python None Keyword
By IncludeHelp Last updated : December 07, 2024
Description and Usage
Note: None is not a keyword – we are just considering & writing it as a keyword which is a replacement of null (in C/C++).
"None" (case-sensitive) is an object of its own datatype, the NoneType, which is similar to null, it is used to define a null value to the variable or represents that a variable does not have any value at all.
None is a type of <class 'NoneType'>.
Syntax
None
Sample Input/Output
Input:
a = None
print("a: ", a);
Output:
a: None
Example 1
Python code to demonstrate example of None keyword.
# python code to demonstrate example of
# None keyword
# type of None
print("type of None: ", type(None))
# declaring a variable and initialize it with None
a = None
# printing value
print("a: ", a)
# checkng None in condition
if a == None:
print("variable \'a\' contains None")
else:
print("variable \'a\' does not contain None")
# assigning a value and rechecking the condition
a = 100
if a == None:
print("variable \'a\' contains None")
else:
print("variable \'a\' does not contain None")
Output
type of None: <class 'NoneType'>
a: None
variable 'a' contains None
variable 'a' does not contain None
Example 2: Assigning None to a Variable
x = None
print(x) # Output: None
Output
None
Example 3: Default Value in Functions
def greet(name=None):
if name is None:
print("Hello, Guest!")
else:
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alex") # Output: Hello, Alice!
Output
Hello, Guest!
Hello, Alex!
Example 4: Checking for None
x = None
if x is None:
print("x has no value.")
else:
print("x has a value.")
Output
x has no value.