In this tutorial you will learn about Comments in python which is used to make your code more readable.
Comments in programming language is used to explain the code and make your program readable so that whenever you see your code you will easily understood.
What is comments in python?
Comments help to explain your thought process and help you and other to understand later about the intension of code. It’s make your code more readable.
Comments in Python is very important because it increase the readability of your code and help you in future for revising your code.
It is important in all kind of project whether they are small, medium or large project. It is important part of your coding and is seen as good practice for developers. Without Comments coding can get confusing.
How to Write Comments in python
There are three way for writing comments in python we can used anyone based on our purpose.
- Single Line Comments – In python you can write single line comments using #(hash). When you write some code or sentence after # than python will ignore them.
#This is my first Comment Print(“Welcome in Programiz.net”)
We can also placed comment after the code so python will ignore rest of line
Print(“Hello programiz”) #Greeting to our programiz
- Multi-Line Comments – In python programming we don’t have Multi-line comment but we can use # function in every line of code for multi-Line comments.
#This is how programiz #you can written #multiline comment Print(“multiline comment”)
You can also use string as multi-line comments because python will string literal until you assign variable to it.
“This is how programiz You can use strings As multiline comment” Print(“Hello Programiz”)
DocString Comments – Python Docstring are the string literals that appear right after the definition of function, class, method & module.
Python 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.
Rules for Docstring
- Either single-line and multi-line comment is used.
- Begin the doc-string with capital letter and end with period.
def add(val1,val2): """calculate the sum of val1 and cal2""" return val1+val2
Def square(n): “””Takes number n, returns square of n “”” Return n**2
Pros of Using Comments
In python program we can use comment to make your program more readable & clear so when next time if you see your code after week or month you will easily understood your code by seeing comments.
Comment can also used for ignoring some line of code when you test your program.
How to use comment in Better way?
- Use comment to describe what function does not how it does.
- Try to Use comment short and clear as possible.