In this post, we learn how to Write Comments In Python. Before we get started, if you want to run a sample python program, please go through the following article: Run Hello World Program In Python.

 

In general, a good programmer should always add some notes explaining in plain language what the code is doing. These short informative notes are called comments.  Comments are lines that exist in computer programs but ignored by compilers and interpreters. Comments are used to tell you what something does in human-readable language, and they also are used to disable parts of your program if you need to remove them temporarily. Writing good comments can save you from a lot of stress in the future.

 

Comments in Python

Comments in Python start with a # and a single whitespace character. Everything after this till the end of the line gets ignored by the compilers. However, they will remain in the source code for programmers to read.  # this is a comment. Now Python interpreter will ignore the entire line and move to the next line. Another good example can be,

Output: this will run

Comments were invented to help developers maintaining and updating their code. Good comments together with well-chosen variable names are necessary for any program longer than a few lines,  otherwise, the program becomes difficult to understand for both the programmer and others.

 

Inline comments

Comments which are just beside the code on the same line, are called inline comments. Generally, they look like this,

Comments should always be short and to the point, Pep 8 suggests that a good program shouldn’t have an inline comment more than 72 characters. As you shouldn’t put more than 72 characters comment in a single line, it’s a good practice to divide them into multiple lines.

 

Multiline Comments in Python

In contrast to other programming languages, Python doesn’t have  any out of the box solution for multiple lines, you just have to begin each line with a hatch # :

Comments can also be used to disable your code temporarily, by merely adding a #  at the beginning of the line which you want to disable and the compiler will skip the line.

Output: this will run

 

Bonus Tip

Almost every modern text editor comes with a shortcut to add comments in your code press  ctrl + / on PC and  cmd + /on Mac, you can disable multiple lines by selecting those lines with the cursor and pressing  ctrl + / on PC and  cmd + /.

Using comments in your programs make it easy for others and your future self to understand the code, So you should always add relevant comments in your code, to make it more robust. Hope this article helped you. If you have any questing regarding it feel free to drop a comment below.

Next Recommended Article: How To Use Variables In Python

Leave a Comment