為什麼 Python 中的 if/while/def/class 語句需要冒號?


在 Python 中,所有這些關鍵字(if、while、def、class 等)都需要冒號以增強可讀性。對於具有語法突出顯示功能的編輯器而言,冒號使其更易於使用;即,它們可以查詢冒號來確定何時需要增加縮排。

讓我們看一個 if 語句的示例:

if a == b
   print(a)

以及:

if a == b:
   print(a)

第二個示例更易於閱讀、理解和縮排。這使得冒號的使用頗為流行。

def 和 if 關鍵字的示例

我們這裡有一個帶有冒號的 def 中的 if 語句,我們將統計元組中某個元素出現的次數:

def countFunc(myTuple, a): count = 0 for ele in myTuple: if (ele == a): count = count + 1 return count # Create a Tuple myTuple = (10, 20, 30, 40, 20, 20, 70, 80) # Display the Tuple print("Tuple = ",myTuple) # The element whose occurrence is to be checked k = 20 print("Number of Occurrences of ",k," = ",countFunc(myTuple, k))

輸出

('Tuple = ', (10, 20, 30, 40, 20, 20, 70, 80))
('Number of Occurrences of ', 20, ' = ', 3)

明確地,對於具有冒號的單個程式中的 def 和 if 語句,程式更易於閱讀和縮排。

類示例

讓我們看一個帶有冒號的類的示例: 

class student: st_name ='Amit' st_age ='18' st_marks = '99' def demo(self): print(self.st_name) print(self.st_age) print(self.st_marks) # Create objects st1 = student() st2 = student() # The getattr() is used here print ("Name = ",getattr(st1,'st_name')) print ("Age = ",getattr(st2,'st_age'))

輸出

('Name = ', 'Amit')
('Age = ', '18')

更新於:2022 年 9 月 20 日

636 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.