Home » Chapter 2 : Programming Basics
Comments
Comments in Python source code files are used to document your code. The Python interpreter ignores comments in your code. Comments can be an entire line in the code file, a partial line in the code file, or multiple lines in a code file.
# This is an entire line comment.
print("This is a literal string that prints to the console.")
print("This is another literal string.") # This is a partial line comment.
print("This is a literal string that prints to the console.")
# This is a multi-line comment
# in which each comment line
# starts with the # symbol.
print("This is a literal string that prints to the console.")
"""
This is a multi-line comment, it can be any number
of lines as long as the comments are between the
two sets of triple-double quotes ...
... including blank lines.
"""
print("This is printing another string.")
Note that a comment can begin with the pound sign (#) symbol. In the example above, we used # for a full line comment or partial line comment. Also, the """ symbol starts and ends a multi-line comment block. The Python interpreter ignores everything enclosed in the comment symbols.
Most IDEs and editors have keyboard shortcuts for commenting code. For example, if you press Ctrl / the line your cursor is on will be commented. Pressing Ctrl / again on the same line will uncomment the line. If you have multiple lines selected (highlighted) and press Ctrl / all of the selected lines will be commented and uncommented if you press Ctrl / again. If you use an IDE or editor other than PyCharm, check its documentation to find the equivalent keyboard shortcut.
There is an ongoing debate about how and where to comment source code. Various opinions exist within different groups in IT. On one end of the debate, some programmers say that your code should be self-documenting. That is, it should be written clearly enough to be obvious to others what it does. On the other end of the debate, some programmers say you should heavily comment source code to try to eliminate ambiguity.
I land in the middle of the two ends of the debate. Either end can be extreme. I think commenting is important to help others who may have to read or maintain your code understand complex constructs, calculations, etc. If you find yourself writing code that would be difficult for others to understand (because it is complex, unorthodox, out of coding standards, etc.), then commenting on it would be very beneficial. On the other hand, if you find yourself writing code like that, it would be wise to reconsider the design and approach to solving the problem.