python:第十九章:数据类型之None
一,什么是None?
None表示空值,其类型为NoneType,
内存中值为None的对象是同一个实例
1
2
3
4
5
6
7
8
9
|
# None的类型 print ( "None的类型:" , type ( None )) # 输出 <class 'NoneType'> # 值为None的对象是同一个实例, # 由于内存None只有一个,所以a is b的结果为True a = None b = None print ( "a == b:" ,a = = b) # 输出 True print ( "a is b:" ,a = = b) # 输出 True |
运行结果:
None的类型: <class 'NoneType'>
a == b: True
a is b: True
二,None的比较:
None 在判断语句中,None相当于False,做not运算后结果为True
判断一个变量是否None,用is运算符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# None 在判断语句中,None相当于False,做not运算后结果为True print ( "not a:" , not a) # 输出 True # 判断一个变量是否None,用is运算符 c = None d = 0 print ( "c is None:" , c is None , ",d is None:" , d is None ) # None并不等于False,两者类型也不同 print ( "None == False:" , None = = False ) # 输出 False # None不等于空字符串,两者类型也不同 print ( "None == '':" , None = = '') # 输出 False # None不等于0,两者类型也不同 print ( "None == 0:" , None = = 0 ) # 输出 False |
运行结果:
not a: True
c is None: True ,d is None: False
None == False: False
None == '': False
None == 0: False
说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/15/python-shu-ju-lei-xing-zhi-none/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
三,函数返回None
函数返回为空和不返回时,都相当于return None
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# 函数返回为空,相当于return None def addFunc(a,b): return # 函数没有返回,也相当于return None def addFunc2(a,b): c = a + b res = addFunc( 1 , 2 ) print ( "res:" , res) # 输出None print ( "res的类型:" , type (res)) # 输出 <class 'NoneType'> res2 = addFunc2( 1 , 2 ) print ( "res2:" , res2) # 输出None print ( "res2的类型:" , type (res2)) # 输出 <class 'NoneType'> |
运行结果:
res: None
res的类型: <class 'NoneType'>
res2: None
res2的类型: <class 'NoneType'>