Python中的關鍵字是Python的保留字。用戶借助這些關鍵字可以實現程序的相關功能,Python程序解釋器通過這些關鍵字來定義程序的機構,知道用戶要實現的程序功能。我們在定義程序的變量、類名及其他Python對象時不能使用這些關鍵字。
在最新的Python中,共定義了35個關鍵字。
我們可以使用Python中提供的help()和keywords命令查看這些關鍵字。
這些關鍵字的主要用途簡單介紹如下:
序號 | 關鍵字 | 用途 | 示例 |
---|---|---|---|
1 | False | 表示邏輯假 | x = False |
2 | class | 用于定義一個類 |
class Student: |
3 | from | 用于從某模塊中導入類 | from collections import OrderedDict |
4 | or | 邏輯運算符:或 | x = True or False |
5 | None | NoneType對象的實例,可以簡單認為相當于其他語言中的null | x = None |
6 | continue | 用于while或for循環(huán)中,用于結束本次循環(huán)而繼續(xù)下一次循環(huán) | numbers = range(1,11) for number in numbers: if number == 7: continue |
7 | global | 用于定義變量時,可以在在定義變量范圍外使用該變量 |
x = 0 |
8 | pass | 此關鍵字表示什么也不做,用于不準備執(zhí)行任何代碼的情形。 | def Sample: pass |
9 | True | 表示邏輯值真 | x = True |
10 | def | 用于定義一個Python函數 | def MyFunc(): print("www.companysz.com") |
11 | if | 用于表示條件,表示如果,即滿足某種條件時要執(zhí)行其后的語句塊 | s = "武林網VEVB" if s == "武林網VEVB": print("http://www.companysz.com") |
12 | raise | 用于程序中拋出一個異常,類似于Java或C#中的throw語句。 | def myFunc(s): if s!="www.companysz.com": raise Exception("網址不正確。") |
13 | and | 邏輯與運算符。 | url = "www.companysz.com" webname="武林網VEVB" print(url == "www.companysz.com" and webname == "武林網VEVB") |
14 | del | 用于刪除一個對象,如變量,列表,類的實例等。 | s = "www.companysz.com" print(s) del s print(s) #NameError: name "s" is not defined |
15 | import | 用于把程序的模塊或模塊的類導入到當前程序中。 | from collections import OrderedDict |
16 | return | 用于函數中帶出返回值。 | def Add(x,y): return x+y |
17 | as | 用于import,except,with語句中提供一個別名 | from collections import OrderedDict as od |
18 | elif | 相當于else if | x = 3 if x > 3: print("比3大")elif x < 3: print("比3小")else: print("等于3") |
19 | in | 用于檢測集合中的成員 | li = [1,2,3,4,5] if 2 in li : print("OK") |
20 | try | 用于處理異常,把可能發(fā)生異常的語句放在try塊中。 | x = "VeVb.com" try: i = int(x) except:print("error") |
21 | assert | assert語句允許我們在程序中插入調試斷言。如果斷言為真,程序將繼續(xù)運行。否則拋出AssertionError。 | def divide(x, y): assert b!=0 return a / b |
22 | else | 用于if..elif..中,當前邊的條件都不滿足時,將執(zhí)行else后的語句 | 見elif的例子 |
23 | is | 用于判斷兩個變量是否具有相同的數據類型,相當于== | fruits = [‘apple’] fruits1 = [‘apple’] f = fruits print(f is fruits) # True print(fruits1 is fruits) # False |
24 | while | 循環(huán)語句,當條件滿足時,會反復執(zhí)行其語句塊。 | x = 1 sum=0 while x<10: sum += x i+=1 print(sum) |
25 | async | Python3.5新增的關鍵字。用于couroutline函數體中,與asyncio模塊和await關鍵字配合使用。 | import asyncio import time async def ping(url): print(f’Ping Started for {url}’) await asyncio.sleep(1) print(f’Ping Finished for {url}’) async def main(): await asyncio.gather( ping(‘askpython.com’), ping(‘python.org’), ) if __name__ == ‘__main__’: then = time.time() loop = asyncio.get_event_loop() loop.run_until_complete(main()) now = time.time() print(f’Execution Time = {now – then}’) |
26 | await | Python3.5中新增的關鍵字。用于異步處理。 | 參見async中的例子 |
27 | lambda | 用于創(chuàng)建lambda表達式。 |
multiply = lambda a, b: a * b |
28 | with | 用于定義了管理器的上下文中,執(zhí)行相關的語句塊。這類對象必須實現了__enter__()和__exit__()函數。 | with open(‘data.csv’) as file: file.read() |
29 | except | 用于捕獲try塊拋出的異常。 | 見try的例子 |
30 | finally | 用于try..except異常處理,放在finally塊中的語句不管異常是否發(fā)生都會被執(zhí)行,常用語回收釋放資源等。 | def division(x, y): try: return x / y except ZeroDivisionError as e: print(e) return -1 finally: print(‘this will always execute’) print(division(10, 2)) print(division(10, 0)) |
31 | nonlocal | 用于訪問語句塊外的變量。 | def outer(): v = ‘outer’ def inner(): nonlocal v v = ‘inner’ inner() print(v) outer() |
32 | yield | 用于函數體中,逐個返回每個值。 |
def multiplyByTen(*kwargs): |
33 | break | 用于for循環(huán)或while循環(huán),用于終止包含此關鍵字最近循環(huán)的整個循環(huán)。 | i = 1 while i < 100: i+=1 if(i>50): break; |
34 | for | for循環(huán) | sum = 0 for i in range(101): sum += i print(sum) |
35 | not | 邏輯非 | i = not True |
新聞熱點
疑難解答