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')
极客笔记