bool([x])
英文說明:Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.
New in version 2.2.1.
Changed in version 2.3: If no argument is given, this function returns False.
中文說明:將x轉(zhuǎn)換為Boolean類型,如果x缺省,返回False,bool也為int的子類;
參數(shù)x:任意對象或缺省;大家注意到:這里使用了[x],說明x參數(shù)是可有可無的,如果不給任何參數(shù)則會返回False。
bool()
>>>bool(0)
False
>>>bool('abc')
True
>>>bool(' ') #參數(shù)是一個空格,非空。
True
>>>bool('') #參數(shù)為空。
False
>>>bool([])
False
>>>bool()
False
>>>bool(None)
False
>>>issubclass(bool,int) #bool是一個subclass int
True
聰注:
- bool( )函數(shù)返回bool值
- 可以用于判斷是否為空,及判斷輸入是否為空。
- 可用于密碼輸入判斷
案例
def volid(pwd):
p = bool(pwd) #判斷是否為空,為空則返回False。這里應(yīng)該在加一個判斷pwd長度的函數(shù)。
a = any(map(str.isupper,pwd))
b = any(map(str.islower,pwd))
c = any(map(str.isdigit,pwd))
d = not all(map(str.isalnum,pwd))
return all([p,a,b,c,d])
'''
這里的isupper,islower,isdigit,isalnum 函數(shù)都很好理解,就是判斷是不是大
寫,是不是小寫,是不是數(shù)字,是不是全是數(shù)字和字母(反過來就是判斷有沒有其
他符號),而這里的map函數(shù)就是把后面那個集合的每個元素用第一個參數(shù)的函數(shù)
執(zhí)行一遍,返回一個bool類型的集合,最外層的any和all函數(shù)就比較容易理解了,
可以用“或”和“與”來理解,如果參數(shù)集合有一個為真,any函數(shù)就返回true,相當于
把所有元素“或”一下,只有當參數(shù)集合全部為真,all函數(shù)才返回true,其他情況都是
返回false ,所以如果volid函數(shù)傳入一個包含大寫小寫字母數(shù)字和特殊符號的字符串
后,abcd就被賦值為true,最后return true,所以這個函數(shù)就可以判斷密碼夠復
雜。
'''
問題:
上例中,如果要求四項中只需要滿足兩項,函數(shù)該怎么寫比較簡練。
參考資料:
(http://www.pythontab.com/html/2013/hanshu_0122/157.html)
(http://www.jb51.net/article/64516.htm)