In Python, there is a special value called “None” that represents the absence of a value or the null value. It is used to indicate that a variable does not have any assigned value. None is a built-in constant, and it is of the type “NoneType.”
Here’s the syntax for using None
in Python:
# Assigning None to a variable
my_variable = None
Checking if a variable is None
if my_variable is None:
print("my_variable is None")
else:
print("my_variable has a value")
The function that returns None
def my_function():
# Some code here...
return None
result = my_function()
if result is None:
print("The function returned None")
else:
print("The function returned a value")
In the code above, None
is assigned to the variable my_variable
, and then we check if it’s None
using the is
keyword. The function my_function
explicitly returns None
, which is later checked in the if
statement.
Note: Use is
when checking for None
, as it ensures you are comparing the identity of the object and not just its value. The is
operator checks if two variables refer to the same object in memory, while the ==
operator checks if the values of the two objects are the same.
Python null value example
Here’s an example that demonstrates the use of None
as the null value in Python:
# Function square root of a number (positive numbers only)
def find_square_root(number):
if number >= 0:
return number ** 0.5
else:
return None
# Test cases
n1 = 16
n2 = -25
result1 = find_square_root(n1)
if result1 is None:
print("The square root of", n1, "is not defined for negative numbers.")
else:
print("The square root of", n1, "is", result1)
result2 = find_square_root(n2)
if result2 is None:
print("The square root of", n2, "is not defined for negative numbers.")
else:
print("The square root of", n2, "is", result2)
Output:
In this example, we have a function find_square_root
that calculates the square root of a given number. However, it is designed to handle only positive numbers. If a negative number is passed to the function, it returns None
.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.