bool是Boolean的縮寫,只有真(True)和假(False)兩種取值
bool函數只有一個參數,並根據這個參數的值返回真或者假。
1.當對數字使用bool函數時,0返回假(False),任何其他值都返回真。
1
2
3
4
5
6
7
8
|
>>>
bool
(
0
)
False
>>>
bool
(
1
)
True
>>>
bool
(
-
1
)
True
>>>
bool
(
21334
)
True
|
2.當對字符串使用bool函數時,對於沒有值的字符串(也就是None或者空字符串)返回False,否則返回True。
1
2
3
4
5
6
7
8
|
>>>
bool
('')
False
>>>
bool
(
None
)
False
>>>
bool
(
'asd'
)
True
>>>
bool
(
'hello'
)
True
|
3.bool函數對於空的列表,字典和元祖返回False,否則返回True。
1
2
3
4
5
6
|
>>> a
=
[]
>>>
bool
(a)
False
>>> a.append(
1
)
>>>
bool
(a)
True
|
4.用bool函數來判斷一個值是否已經被設置。
1
2
3
4
5
6
7
8
|
>>> x
=
raw_input
(
'Please enter a number :'
)
Please enter a number :
>>>
bool
(x.strip())
False
>>> x
=
raw_input
(
'Please enter a number :'
)
Please enter a number :
4
>>>
bool
(x.strip())
True
|