
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Colons Required for if, while, def, and 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')
Advertisements