Online Tutorials & Training Materials | STechies.com
Register Login

Null Object in Python

|| 0

Null Object in Python
Stechies

Python Null or None Object

In python, the None keyword is use to define the Null value of an object or variable; it is an object and a NoneType data type.

Note:

  • We can define None to any variable or object.
  • None is not equal to 0
  • None is not equal to FALSE
  • None is not equal to empty string
  • None is only equal to None

We can check None by keyword “is” and syntax “==”

Example:

# Python program to check None value

# initialized a variable with None value

myval = None

# Check by using 'is' keyword

if myval is None:

 print('myval is None')

else:

 print('myval is not None')

# Check by using '==' syntax

if myval == None:

 print('myval is None')

else:

 print('myval is not None')

Output:

myval is None

myval is None

Check None type

# Python program to check None value

# initialized a variable with None value

myval = None

print(type(myval))

Output:

<class 'NoneType'>

Check if None is equal to None

# Python program to check None value

# initialized a variable with None value
myval = None

if None is None:
    print('None is None')
else:
    print('None is Not None')

print(None == None)

Output:

None is None

True

Check if None is equal to False

Example:

# initialized a variable with None value
myval = None

if myval == False:
    print('None is equal to False')
else:
    print('None is Not Equal to False')

print(None == False)

Output:

None is Not Equal to False

False

Check if None is equal to empty string

# Inilised a variable with None value
myval = ''

if myval == None:
    print('None is equal to empty string')
else:
    print('None is Not Equal to empty string')

print(None == myval)

Output:

None is Not Equal to empty string

False

Return None or Null from function

# Python program to check None value
# Using custom function

# initialized a variable with None value
myval = None

# Define function
def nullfunction(myval):
    
    # Check if variable is None
    if myval is None:
        result = None
    else:
        result = 'myval is not None'
    return result

print('Output: ',nullfunction(myval))

Output: 

Output: None