In this tutorial you will learn about python comments and it’s types. The comments used to make your code more readable for better understanding.
Adding comments in coding is good habits because whenever you see your code it will easy for you to remember your code and it is easy for other also to understand the intension of your code, whom you are going to work as a team.
What is comments in python?
The single line sentence after # character is define as comment in python. The comment is not an executing code in python but it used to put explanation about what particular line of code does in your program.
Types of Comments in python
The three types of comments in python are inline comment, block comment and doctsrings comment.
- Python inline comments
Putting a comment after the code in same line in python is called as python inline comment. In python we used # character for single-line comment.
Print(“Hello programiz”) #Greeting to our programiz
- Python block comments
Python block comment is also know as python block comment. In python you can write block comment by using #(hash) character in every new line because python programming does not have any default features for writing block comments.
Python does not have block comment by default, but you can use some good python editor for this features of python block comments. The only way of writing python block comments is appending # character as a prefix in every new line of python.
# First line of block comment # Second line of block comment # Third line of block comment
You can also use string as block comments because python will ignore string literal until you assign variable to it, but this is not the correct way for commenting block in python.
- Python docstrings comments
Python docstrings also know as Document string. It is used for documenting function, class, method & module in python.
It has built-in concept called docstring. A docstring is added as a comment right below the function, module and object head and describe what the function, module and object does.
def add(val1,val2): """calculate the sum of val1 and cal2""" return val1+val2 print(add.__doc__)
Def square(n): “””Takes number n and returns square of n “”” Return n*n
Best practice of comments
- Use comment to explain about what function does not how it does.
- Try to Use comment short and as possible.