逻辑值(bool)用来表示: 对与错, 真与假, 空与非空等概念
逻辑值包含两个值:
True
诸如非空的量(string tuple list set dictionary等)以及非零的数(负数和正数都为True)
False
0
None
空的量
逻辑值的作用
主要用于判断语句中 if else
1.用来判断一个字符串是否为空
2.一个运算结果是否为0
3.一个表达式是否可用
4.判断函数的返回值
#!/usr/bin/python
l1 = [[], [1,2,3], (), (1, 2), {}, {1:"good"}, None, -1, 0, 1, "", "hello"]
for l in l1 :
if l :
print l, " is True"
else :
print l, " is False"
输出结果:
[] is False
[1, 2, 3] is True
() is False
(1, 2) is True
{} is False
{1: 'good'} is True
None is False
-1 is True
0 is False
1 is True
is False #字符串为空
hello is True
以上结果可以验证True和False的分类
函数的返回值None
函数的默认返回值为None, 可以通过此方法来验证
#!/usr/bin/python
def fun(x, y) :
if x+y >= 10 :
return x+y
else :
print "less than 10"
if fun(3, 5) :
print "True"
else :
print "False"
输出结果:
less than 10 #return x+y 没有执行,默认返回None,因此if判断调用函数的时候,为false
False