In Python, there is a special value called None
that is used to represent null or absence of a value. You can use None
to assign null to a variable or as a placeholder for a value that has not been assigned yet. Here’s how you can assign a null value in Python:
# Method 1: Direct assignment of None
variable_name = None
# Method 2: Assigning None to a variable using a function or condition
def return_none():
return None
another_variable = return_none()
# Method 3: Assigning None conditionally
condition = False
some_value = None if condition else "not null value"
Note: None
is not the same as an empty string (""
) or a zero (0
). It is a special constant that represents the absence of a value. Also, keep in mind that None
is a singleton object, meaning there is only one instance of None
in memory, so you can compare None
using the is
keyword:
variable_name = None
if variable_name is None:
print("The variable is assigned to None.")
else:
print("The variable has some value.")
Output: The variable is assigned to None.
Assign null value in Python example
Here’s an example of assigning a None
value to a variable in Python:
# Assigning None to a variable
name = None
age = None
is_student = None
# Printing the variables
print("Name:", name)
print("Age:", age)
print("Is Student:", is_student)
Output:
In this example, we have three variables name
, age
, and is_student
, all of which are assigned the value None
, indicating that they have no specific value assigned and are essentially null.
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.