国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > Python > 正文

Python中的關(guān)鍵字

2023-04-27 19:03:18
字體:
供稿:網(wǎng)友

Python中的關(guān)鍵字是Python的保留字。用戶借助這些關(guān)鍵字可以實現(xiàn)程序的相關(guān)功能,Python程序解釋器通過這些關(guān)鍵字來定義程序的機構(gòu),知道用戶要實現(xiàn)的程序功能。我們在定義程序的變量、類名及其他Python對象時不能使用這些關(guān)鍵字。

在最新的Python中,共定義了35個關(guān)鍵字。

Python中的關(guān)鍵字

我們可以使用Python中提供的help()和keywords命令查看這些關(guān)鍵字。

Python中使用help()來查看關(guān)鍵字

這些關(guān)鍵字的主要用途簡單介紹如下:

Python中關(guān)鍵字及主要用途
序號 關(guān)鍵字 用途 示例
1 False 表示邏輯假 x = False
2 class 用于定義一個類

class Student:
    pass

3 from 用于從某模塊中導(dǎo)入類 from collections import OrderedDict
4 or 邏輯運算符:或 x = True or False
5 None NoneType對象的實例,可以簡單認為相當(dāng)于其他語言中的null x = None
6 continue 用于while或for循環(huán)中,用于結(jié)束本次循環(huán)而繼續(xù)下一次循環(huán) numbers = range(1,11)
for number in numbers:
    if number == 7:
        continue
7 global 用于定義變量時,可以在在定義變量范圍外使用該變量

x = 0
def add():
global x
x = x + 10
add()
print(x) # 10

8 pass 此關(guān)鍵字表示什么也不做,用于不準備執(zhí)行任何代碼的情形。 def Sample:
   pass
9 True 表示邏輯值真 x = True
10 def 用于定義一個Python函數(shù) def MyFunc():
  print("www.survivalescaperooms.com")
11 if 用于表示條件,表示如果,即滿足某種條件時要執(zhí)行其后的語句塊 s = "武林網(wǎng)VEVB"
if s == "武林網(wǎng)VEVB":
   print("http://www.survivalescaperooms.com")
12 raise 用于程序中拋出一個異常,類似于Java或C#中的throw語句。 def myFunc(s):
   if s!="www.survivalescaperooms.com":
      raise Exception("網(wǎng)址不正確。")
13 and 邏輯與運算符。 url = "www.survivalescaperooms.com"
webname="武林網(wǎng)VEVB"
print(url == "www.survivalescaperooms.com" and webname == "武林網(wǎng)VEVB")
14 del 用于刪除一個對象,如變量,列表,類的實例等。 s = "www.survivalescaperooms.com"
print(s)
del s
print(s) #NameError: name "s" is not defined
15 import 用于把程序的模塊或模塊的類導(dǎo)入到當(dāng)前程序中。 from collections import OrderedDict
16 return 用于函數(shù)中帶出返回值。 def Add(x,y): return x+y
17 as 用于import,except,with語句中提供一個別名 from collections import OrderedDict as od
18 elif 相當(dāng)于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語句允許我們在程序中插入調(diào)試斷言。如果斷言為真,程序?qū)⒗^續(xù)運行。否則拋出AssertionError。 def divide(x, y): assert b!=0 return a / b
22 else 用于if..elif..中,當(dāng)前邊的條件都不滿足時,將執(zhí)行else后的語句 見elif的例子
23 is 用于判斷兩個變量是否具有相同的數(shù)據(jù)類型,相當(dāng)于== fruits = [‘apple’]
fruits1 = [‘apple’]
f = fruits
print(f is fruits) # True
print(fruits1 is fruits) # False
24 while 循環(huán)語句,當(dāng)條件滿足時,會反復(fù)執(zhí)行其語句塊。 x = 1
sum=0
while x<10: sum += x i+=1
print(sum)
25 async Python3.5新增的關(guān)鍵字。用于couroutline函數(shù)體中,與asyncio模塊和await關(guān)鍵字配合使用。 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中新增的關(guān)鍵字。用于異步處理。 參見async中的例子
27 lambda 用于創(chuàng)建lambda表達式。

multiply = lambda a, b: a * b
print(multiply(8, 6)) # 48

28 with 用于定義了管理器的上下文中,執(zhí)行相關(guān)的語句塊。這類對象必須實現(xiàn)了__enter__()和__exit__()函數(shù)。 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 用于函數(shù)體中,逐個返回每個值。

def multiplyByTen(*kwargs):
    for i in kwargs:
        yield i * 10
a = multiplyByTen(4, 5,)
# a is generator object, an iterator
# showing the values
for i in a:
    print(i) # Output 40 50

33 break 用于for循環(huán)或while循環(huán),用于終止包含此關(guā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
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 富阳市| 津市市| 义马市| 垦利县| 林芝县| 中卫市| 隆回县| 嘉义县| 兴山县| 英吉沙县| 新乡市| 龙川县| 遵义市| 延寿县| 修文县| 六枝特区| 彰化市| 涪陵区| 舒城县| 白水县| 绿春县| 雷山县| 万安县| 南充市| 石楼县| 松阳县| 兴业县| 南川市| 富民县| 慈利县| 来安县| 伊春市| 乌兰浩特市| 唐河县| 扎兰屯市| 泊头市| 太和县| 铜川市| 宝清县| 崇仁县| 洪湖市|