Python 關鍵字
像其他語言一樣,Python 也有一些保留字。這些單詞具有一些特殊含義。有時它可能是一個命令,或一個引數等。我們不能將關鍵字用作變數名。
Python 關鍵字如下:
| True | False | class | def | return |
| if | elif | else | try | except |
| raise | finally | for | in | is |
| not | from | import | global | lambda |
| nonlocal | pass | while | break | continue |
| and | with | as | yield | del |
| or | assert | None |
True & False 關鍵字
True 和 False 是 Python 中的真值。比較運算子返回 True 或 False。布林變數也可以儲存它們。
示例程式碼
#Keywords True, False print(5 < 10) #it is true print(15 < 10) #it is false
輸出
True False
class、def、return 關鍵字
class 關鍵字用於在 Python 中定義新的使用者自定義類。def 用於定義使用者自定義函式。return 關鍵字用於從函式返回並向呼叫函式傳送值。
示例程式碼
#Keywords Class, def, return
class Point: #Class keyword to define class
def __init__(self, x, y): #def keyword to define function
self.x = x
self.y = y
def __str__(self):
return '({},{})'.format(self.x, self.y) #return Keyword for returning
p1 = Point(10, 20)
p2 = Point(5, 7)
print('Points are: ' + str(p1) + ' and ' + str(p2))
輸出
Points are: (10,20) and (5,7)
if、elif、else 關鍵字
這三個關鍵字用於條件分支或決策。當 if 語句的條件為真時,它進入 if 程式碼塊。當它為假時,它搜尋另一個條件,因此如果有一些 elif 程式碼塊,它會用它們檢查條件。最後,當所有條件都為假時,它進入 else 部分。
示例程式碼
#Keywords if, elif, else
defif_elif_else(x):
if x < 0:
print('x is negative')
elif x == 0:
print('x is 0')
else:
print('x is positive')
if_elif_else(12)
if_elif_else(-9)
if_elif_else(0)
輸出
x is positive x is negative x is 0
try、except、raise、finally 關鍵字
這些關鍵字用於處理 Python 中的不同異常。在 try 程式碼塊中,我們可以編寫一些程式碼,這些程式碼可能會 raise 一些異常,並使用 except 程式碼塊來處理它們。即使存在未處理的異常,finally 程式碼塊也會執行。
示例程式碼
#Keywords try, except, raise, finally
defreci(x):
if x == 0:
raise ZeroDivisionError('Cannot divide by zero') #raise an exception
else:
return 1/x
deftry_block_example(x):
result = 'Unable to determine' #initialize
try: #try to do next tasks
result = reci(x)
except ZeroDivisionError: #except the ZeroDivisionError
print('Invalid number')
finally: # Always execute the finally block
print(result)
try_block_example(15)
try_block_example(0)
輸出
0.06666666666666667 Invalid number Unable to determine
for、in、is、not 關鍵字
for 關鍵字基本上是 Python 中的 for 迴圈。in 關鍵字用於檢查某個元素在某些容器物件中的參與情況。還有另外兩個關鍵字,分別是 is 和 not。is 關鍵字用於測試物件的標識。not 關鍵字用於反轉任何條件語句。
示例程式碼
#Keywords for, in, is, not
animal_list = ['Tiger', 'Dog', 'Lion', 'Peacock', 'Snake']
for animal in animal_list: #iterate through all animals in animal_list
if animal is 'Peacock': #equality checking using 'is' keyword
print(animal + ' is a bird')
elif animal is not 'Snake': #negation checking using 'not' keyword
print(animal + ' is mammal')
輸出
Tiger is mammal Dog is mammal Lion is mammal Peacock is a bird
from、import 關鍵字
import 關鍵字用於將某些模組匯入到當前名稱空間中。from…import 用於從模組匯入一些特殊屬性。
示例程式碼
#Keywords from, import from math import factorial print(factorial(12))
輸出
479001600
global 關鍵字
global 關鍵字用於表示在程式碼塊內部使用的變數是全域性變數。當不存在 global 關鍵字時,變數將表現為只讀。要修改值,我們應該使用 global 關鍵字。
示例程式碼
#Keyword global glob_var = 50 defread_global(): print(glob_var) def write_global1(x): global glob_var glob_var = x def write_global2(x): glob_var = x read_global() write_global1(100) read_global() write_global2(150) read_global()
輸出
50 100 100
lambda 關鍵字
lambda 關鍵字用於建立一些匿名函式。對於匿名函式,沒有名稱。它就像一個行內函數。匿名函式中沒有 return 語句。
示例程式碼
#Keyword lambda square = lambda x: x**2 for item in range(5, 10): print(square(item))
輸出
25 36 49 64 81
nonlocal 關鍵字
nonlocal 關鍵字用於宣告巢狀函式中的變數不是區域性變數。因此,它是外部函式的區域性變數,但不是內部函式的區域性變數。此關鍵字用於修改某些非區域性變數的值,否則它處於只讀模式。
示例程式碼
#Keyword nonlocal
defouter():
x = 50
print('x from outer: ' + str(x))
definner():
nonlocal x
x = 100
print('x from inner: ' + str(x))
inner()
print('x from outer: ' + str(x))
outer()
輸出
x from outer: 50 x from inner: 100 x from outer: 100
pass 關鍵字
pass 關鍵字基本上是 Python 中的空語句。當執行 pass 時,什麼也不會發生。此關鍵字用作佔位符。
示例程式碼
#Keyword pass defsample_function(): pass #Not implemented now sample_function()
輸出
(No Output will come)
while、break、continue、and 關鍵字
while 是 Python 中的 while 迴圈。break 語句用於退出當前迴圈,控制權移動到緊接在迴圈下方的部分。continue 用於忽略當前迭代。它移動到不同迴圈中的下一個迭代。
and 關鍵字用於 Python 中的邏輯與運算,當兩個運算元都為真時,它返回 True 值。
示例程式碼
#Keywords while, break, continue, and
i = 0
while True:
i += 1
if i>= 5 and i<= 10:
continue #skip the next part
elifi == 15:
break #Stop the loop
print(i)
輸出
1 2 3 4 11 12 13 14
with、as 關鍵字
with 語句用於將一組程式碼的執行包裝在由上下文管理器定義的方法中。as 關鍵字用於建立別名。
示例程式碼
#Keyword with, as
with open('sampleTextFile.txt', 'r') as my_file:
print(my_file.read())
輸出
Test File.
We can store different contents in this file
~!@#$%^&*()_+/*-+\][{}|:;"'<.>/,'"]
yield 關鍵字
yield 關鍵字用於返回生成器。生成器是一個迭代器。它一次生成一個元素。
示例程式碼
#Keyword yield
defsquare_generator(x, y):
for i in range(x, y):
yield i*i
my_gen = square_generator(5, 10)
for sq in my_gen:
print(sq)
輸出
25 36 49 64 81
del、or 關鍵字
del 關鍵字用於刪除物件的引用。or 關鍵字執行邏輯或運算。當至少一個運算元為真時,答案將為真。
示例程式碼
#Keywords del, or
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
index = []
for i in range(len(my_list)):
if my_list[i] == 30 or my_list[i] == 60:
index.append(i)
for item in index:
del my_list[item]
print(my_list)
輸出
[10, 20, 40, 50, 60, 80, 90, 100, 110]
assert 關鍵字
assert 語句用於除錯。當我們想要檢查內部狀態時,可以使用 assert 語句。當條件為真時,它不返回任何內容,但當它為假時,assert 語句將引發 AssertionError。
示例程式碼
#Keyword assert val = 10 assert val > 100
輸出
---------------------------------------------------------------------------
AssertionErrorTraceback (most recent call last)
<ipython-input-12-03fe88d4d26b> in <module>()
1#Keyword assert
2val=10
----> 3assertval>100
AssertionError:
None 關鍵字
None 是 Python 中的一個特殊常量。它表示空值或值缺失。我們不能建立多個 none 物件,但可以將其分配給不同的變數。
示例程式碼
#Keyword None
deftest_function(): #This function will return None
print('Hello')
x = test_function()
print(x)
輸出
Hello None
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP