This is a detailed guide on Python Comments. Learn how you can write a single line or multi-line comments within your python code.
Comments can be written in your Python code for different purposes. You can make your code more readable to yourself as well as for other code readers or developers with comments. Hence, comments are a good way to explain your code. One can also use comments to prevent some part of your code from being executed while you’re testing and playing with different things in your code.
Python offers you to write single-line as well as multi-line comments. Both of these are explained below with examples.
Single line comments start with the
#The Print Statement
print("A Single-Line Comment Illustration")
In the small code snippet written above the line that begins with the
# symbol is basically a comment and the Python compiler will not read it and will simply execute the other lines of code.
Given below is another code snippet that has two print statements. One is being commented while the other is not. So, in the screenshot of the output, only the un-commented print statement is being executed.
You can write multi-line comments in two different ways in Python. The first way again using the # symbol in every new line of your multi-line comment as specified in the following code snippet.
#This is a
#using first method
Although this way is completely valid yet it is not the appropriate way. Imagine the case when you have a very large section of your code that you might be wanted to comment on for testing purposes. You simply won’t write # symbol in front of every line of code.
So, there’s a better way and it’s called multi-line string comment. This is illustrated below.
This is also a
but you only specify symbols
at the start
and at the end
You just need to write the single quote (
') symbol thrice at the starting and ending position of the code portion that you want to comment on.
The following screenshot also illustrated the multi-line comments in python. You can clearly see only one statement that is out the scope of the multi-line comment is being executed.
If you find this article useful, do share it with others who might be willing to learn Python. If you have any questions related to this article, feel free to ask in the comments section.
Don’t forget to Subscribe to WTMatter!