Tuesday 21 September 2021

Python: What is None

None keyword is used to represent undefined state, absence of a value or null value. It is similar to null value in other programming languages like Java.

 

Can I assign None to a variable?

Yes, you can.

 

none_1.py

a = None

print(a)

 

Output

None

 

Important point to remember

None is not same as zero, False, empty string,

 

How to check whether a variable is None or not?

Using ‘is’ or == operator, you can check whether a variable is None or not.

 

none_2.py

def is_none(x, variable_name):
    if x is None:
        print(variable_name, ' is set to None')
    else:
        print(variable_name, ' is not None')

a = None
b = False
c = 0
d = ""
e = 0.00

is_none(a, 'a')
is_none(b, 'b')
is_none(c, 'c')
is_none(d, 'd')
is_none(e, 'e')

Output

a  is set to None
b  is not None
c  is not None
d  is not None
e  is not None


None comparison support both is and == operator, you will yield the same result as above by comparing with ==.

 

none_3.py

def is_none(x, variable_name):
    if x == None:
        print(variable_name, ' is set to None')
    else:
        print(variable_name, ' is not None')

a = None
b = False
c = 0
d = ""
e = 0.00

is_none(a, 'a')
is_none(b, 'b')
is_none(c, 'c')
is_none(d, 'd')
is_none(e, 'e')


Output

a  is set to None
b  is not None
c  is not None
d  is not None
e  is not None


If a functions doesn’t return anything explicitly, then None is returned by default.

 

none_4.py

def say_hello():
    print('Hello')

print(say_hello())


Output

Hello
None


None==None (or) None is None evaluate to True

 

none_5.py

a = None
b = None

print('a == b', (a == b))
print('a is b', (a is b))


Output

a == b True
a is b True


None belongs to the type ‘NoneType’

none_6.py

print(type(None))


Output

<class 'NoneType'>









 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment