Python必須了解的35個(gè)關(guān)鍵詞
每種編程語(yǔ)言都會(huì)有一些特殊的單詞,稱(chēng)為關(guān)鍵詞。對(duì)待關(guān)鍵詞的基本要求是,你在命名的時(shí)候要避免與之重復(fù)。本文將介紹一下Python中的關(guān)鍵詞。關(guān)鍵詞不是內(nèi)置函數(shù)或者內(nèi)置對(duì)象類(lèi)型,雖然在命名的時(shí)候同樣也最好不要與這些重名,但是,畢竟你還可以使用與內(nèi)置函數(shù)或者內(nèi)置對(duì)象類(lèi)型重名的名稱(chēng)來(lái)命名。關(guān)鍵詞則不同,它是不允許你使用。
在Python3.8中提供了35個(gè)關(guān)鍵詞,如下所示:
False await else import passNone break except in raiseTrue class finally is returnand continue for lambda tryas def from nonlocal whileassert del global not withasync elif if or yield
如果打算在交互模式里面查看關(guān)鍵詞,可以使用help():
>>> help('keywords')Here is a list of the Python keywords. Enter any keyword to get more help.False await else import passNone break except in raiseTrue class finally is returnand continue for lambda tryas def from nonlocal whileassert del global not withasync elif if or yield
對(duì)每個(gè)關(guān)鍵詞的詳細(xì)說(shuō)明,也可以用help()查看:
>>> help(’pass’) # 敲回車(chē)后出現(xiàn)下面的內(nèi)容The 'pass' statement******************** pass_stmt ::= 'pass''pass' is a null operation — when it is executed, nothing happens. Itis useful as a placeholder when a statement is required syntactically,but no code needs to be executed, for example: def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet)
除了上面的方法之外,還有一個(gè)標(biāo)準(zhǔn)庫(kù)的模塊keyword提供了關(guān)鍵詞查詢(xún)功能。
>>> import keyword>>> keyword.kwlist[’False’, ’None’, ’True’, ’and’, ’as’, ’assert’, ’async’, ...>>> len(keyword.kwlist)35
那么,這些關(guān)鍵詞如何使用?在什么情景下應(yīng)用?下面以示例的方式對(duì)部分關(guān)鍵詞進(jìn)行說(shuō)明。
True、False和None
True和False是布爾類(lèi)型的兩個(gè)值,注意必須首字母大寫(xiě)。
>>> x = True>>> x is TrueTrue>>> y = False>>> y is FalseTrue
如果我們要判斷某個(gè)對(duì)象的布爾值是True還是False,可以使用bool()函數(shù)實(shí)現(xiàn),例如:
>>> x = 'this is a truthy value'>>> x is TrueFalse>>> bool(x) is TrueTrue>>> y = '' # 這個(gè)是假>>> y is FalseFalse>>> bool(y) is FalseTrue
注意,如果向bool()傳入的參數(shù)是0, '', {}, []中的任何一個(gè),返回值都是False。
在條件語(yǔ)句中,本來(lái)是要判斷條件是否為T(mén)rue,但是,通常不需要直接與True或者False進(jìn)行比較,依靠Python解析器自動(dòng)進(jìn)行條件判斷。
>>> x = 'this is a truthy value'>>> if x is True: # 不要這么做... print('x is True')...>>> if x: # 應(yīng)該如此寫(xiě)... print('x is truthy')...x is truthy
None這個(gè)關(guān)鍵詞,在Python中表示沒(méi)有值,其他語(yǔ)言中,同樣的含義可能會(huì)用null,nil,none,undef,undefined等。None也是函數(shù)中沒(méi)有return語(yǔ)句的時(shí)候默認(rèn)返回值。
>>> def func():... print('hello')...>>> x = func()hello>>> print(x)None>>> def func():... print('hello')...>>> x = func()hello>>> print(x)None
and、or、not、in、is
這幾個(gè)關(guān)鍵詞,其實(shí)都對(duì)應(yīng)著數(shù)學(xué)中的操作符,如下表所示。
數(shù)據(jù)符合 關(guān)鍵詞 AND, ∧ and OR, ∨ or NOT, ¬ not CONTAINS, ∈ in IDENTITY is
Python代碼具有很強(qiáng)的可讀性,通過(guò)關(guān)鍵詞就能一目了然曉得是什么操作。
這幾個(gè)關(guān)鍵詞比較好理解,這里僅提醒注意在Python中有一個(gè)著名的短路運(yùn)算,例如and:
<expr1> and <expr2> 不要將上面的式子理解成兩邊都是真的時(shí)候返回True。對(duì)此,在**《Python大學(xué)實(shí)用教程》**一書(shū)中有非常詳細(xì)的說(shuō)明,請(qǐng)參閱。另外一個(gè)就是or,也存在短路運(yùn)算。
break、continue和else這幾個(gè)是經(jīng)常用于循環(huán)語(yǔ)句的關(guān)鍵詞。
break 的作用是終止當(dāng)前循環(huán),其使用的基本格式:
for <element> in <container>: if <expr>: break舉個(gè)例子:>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> sum = 0>>> for num in nums:... sum += num... if sum > 10:... break...>>> sum15
continue則是要跳過(guò)某些循環(huán),然后讓循環(huán)繼續(xù)。
for <element> in <container>: if <expr>:continue
else在條件語(yǔ)句中有,這里提到它,是在循環(huán)語(yǔ)句中,它的作用是當(dāng)循環(huán)結(jié)束后還要繼續(xù)執(zhí)行的代碼。
在for循環(huán)中,使用格式如下:
for <element> in <container>: <statements>else: <statements>
在while循環(huán)中,使用格式如下:
while <expr>: <statements>else: <statements>
例如,有時(shí)候我們要在循環(huán)語(yǔ)句中使用一個(gè)旗幟變量:
>>> for n in range(2, 10):... prime = True... for x in range(2, n):... if n % x == 0:... prime = False... print(f'{n} is not prime')... break... if prime:... print(f'{n} is prime!')...2 is prime!3 is prime!4 is not prime5 is prime!6 is not prime7 is prime!8 is not prime9 is not prime
在上面的代碼中,prime就是一個(gè)旗幟變量,如果循環(huán)正常結(jié)束,prime的值就是True,否則,就是False。如果從循環(huán)中退出了,第8行判斷這個(gè)變量的值,如果為T(mén)rue則打印相應(yīng)內(nèi)容。
對(duì)于上面的代碼,如果用else改寫(xiě),可以更簡(jiǎn)潔,并且可讀性更強(qiáng)。
>>> for n in range(2, 10):... for x in range(2, n):... if n % x == 0:... print(f'{n} is not prime')... break... else:... print(f'{n} is prime!')...2 is prime!3 is prime!4 is not prime5 is prime!6 is not prime7 is prime!8 is not prime9 is not prime
以上就是Python必須了解的35個(gè)關(guān)鍵詞的詳細(xì)內(nèi)容,更多關(guān)于Python 關(guān)鍵詞的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
