为什么 Python 中的 if/while/def/class 语句需要冒号?
pythonprogrammingserver side programming更新于 2023/11/29 6:48:00
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')