Comments are lines of text that are ignored by the Python interpreter. They are used to add notes to code for documentation purposes or to temporarily disable a piece of code for testing purposes.

There are two types of comments:

  1. Single-line comments
  2. Multi-line comments

single line comments

Single-line comments start with the # character and continue until the end of the line. When the Python interpreter encounters a # character, it ignores the rest of the line, treating it as a comment.

#This line is a comment, it will be ignored
print('Hello, World!')

In the above example, the first line is a comment. The comment is placed on a line of its own, however, comments can also be placed at the end of a statement, this is usually used to briefly describe what that particular statement is doing.

print('Hello, World!') #displays hello world to the console.

In the above example, the comment starts at the end of the print statement, in such a situation, the interpreter executes only the piece of code appearing on the left of the # character, the rest are ignored.

A combination of comments appearing on lines of their own and others mixed with the statement allows the programmer to effectively document the program using whichever mode is more relevant.  

#a program to add two numbers.

def add(a, b):
   #this function calculates the sum of a and b
   return f'{a} + {b} = {a + b}' #Return a formatted result of the addition operation. 

print(add(50, 60)) #get the sum of 50 and 60

In the above example, we have used both modes of commenting, where some comments are on their own lines and others appear after a statement.

Use single-line comments to Disable execution

As we mentioned earlier, comments have two major purposes.

  1. Adding notes to the program for documentation purposes.
  2. Disabling execution of some statements  for testing and debugging purposes.

In all the previous examples, we used single-line comment for documentation, in this section we will look at how they can be used to disable execution.

If the # character is placed in front of a valid statement, the statement will equally be treated as a comment and it will therefore not get executed.

In the following snippet we use a single line comment to stop a statement from being executed

#print('Hello, World!')
print('Goodbye, World!')

In the above case, only the second line is executed.  Without the  leading # character, the first line would have been executed as well.

When the # character is placed in front of a valid statement , the statement is said to be commented.

#def add(a, b):
#   return f'{a} + {b} = {a + b}' 
#add(50, 60)

print('Hello')

Disabling execution by commenting is especially common for debugging purposes as it provides a mechanism for isolating the statements that are likely to be causing the bug. 

Multi-line comments

Although Python does not have a specific syntax for multi-line comments like some other programming languages, triple single or double quotes(''' or """) can be used to create multi-line strings that are not assigned to any variable or used as docstrings.

"""
This is a multi-line comment.
It can span across multiple lines.
Single or double quotes can be used
"""

print('Hello')

It is important to note that the triple quoted string are not comments in the real sense of the word, they actually get executed by the interpreter,  which is not the case with the single line comments(starting with #) which are entirely ignored.  However, since a string which is not assigned to any variable will just be passed through, the triple quotes can effectively be used as comments.

'''
This program calculates the sum
of two numbers a and b.
The add() function implements the
main logic of the addition operation
'''

def add(a, b):
   return f"{a} + {b} = {a + b}"

print(add(10, 20))

The triple quotes can as well be used to stop statements from being executed:

''''
def add(a, b):
   print(a + b)

func()
'''
print('Function add was commented.')

In the above case the function add() is commented.

multiline comments as docstrings

Docstrings are typically triple-quoted comments that appear as the first statement of a function, a class or a module. They are used  for documentation purposes and are included in the help text when we call the help() function on the involved object.

def add(a, b):
   '''returns a formatted result of the addition operation between a and b'''
   return f"{a} + {b} = {a + b}"

help(add)

As you can see above, the first line of the function add() is a triple-quoted string, which is interpreted  as the function's docstring. The help() function includes this string in the help text.

The raw docstring of a given object can be retrieved via its __doc__ attribute, as shown below.

def add(a, b):
   '''returns a formatted result of the addition operation between a and b'''
   return f"{a} + {b} = {a + b}"

print(add.__doc__)

The main differences between docstrings  and regular mult-line comments are listed below:

  • Docstring only appear as the first statement in a function, class or module while comments can appear anywhere in the program.
  • Docstrings are structured and accessible programmatically via the __doc__ attribute or the help() function while comments are unstructured and only meant for human readers.
  • Docstring are specifically meant for documenting a group of code while comments can be used for multiple purposes such as in adding notes,  debugging, testing e.t.c 

Why use comments?

  1. Code Explanation: Comments provide a way to explain the functionality, logic, or intention of your code. They help other developers (including your future self) understand the purpose and implementation of specific code segments. Clear and concise comments can make your code more readable and maintainable.

  2. Documentation: Comments can serve as a form of documentation for your code. They provide high-level descriptions of how different parts of the code work, what functions or classes do, and any important considerations or limitations. Documentation comments can be valuable for future reference or when sharing code with others.

  3. Code Review and Collaboration: Comments aid in the code review process. They allow reviewers to provide feedback, ask questions, or suggest improvements directly in the code. Comments can facilitate collaboration among team members working on the same codebase.

  4. Debugging and Troubleshooting: Comments can be used to temporarily disable or "comment out" lines of code during debugging or troubleshooting. This allows you to isolate problematic code segments without deleting them, making it easier to identify and fix issues.

  5. Future Modifications: Comments can provide hints or suggestions for future modifications or enhancements to the code. They can outline potential improvements or alternative approaches, making it easier to revisit and update the code later.

It's worth noting that while comments are valuable, it's essential to maintain a balance. Over-commenting or including unnecessary comments can clutter the code and make it harder to read. Comments should be clear, concise, and relevant to the code they accompany.

By using comments effectively, you can improve code readability, maintainability, collaboration, and the overall quality of your software projects.