Why are colons required for the if/while/def/class statements in Python?


The colon is required for all these keywords, if, while, def, class, etc in Python to enhance readability. The colon makes it easier for editors with syntax highlighting i.e. they can look for colons to decide when indentation needs to be increased.

Let’s see an example of an if statement −

if a == b
   print(a)

And,

if a == b:
   print(a)

The 2nd example is easier to read, understand and indent. This makes the usage of colon quite popular.

The def and if keyword example

We have an if statement in def here with colon and we will count the occurrences of an element in a Tuple −

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))

Output

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

Definitely, with the colon, the program is easier to read and indent with both def and if statement in a single program.

Class Example

Let’s see an example of a class with the colon 

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'))

Output

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

Updated on: 20-Sep-2022

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements