Sep 14, 2023 3 min read

Fundamentals of Writing Comments in Python

Fundamentals of Writing Comments in Python with our step-by-step tutorial. Using comments is a way to improve the readability of your code.

Fundamentals of Writing Comments in Python
Table of Contents

Before we begin talking about fundamentals of writing comments in Python, let's briefly understand – What is Comments in Python?

When writing Python code, it is always a good idea to keep it clean and easy to understand. Several approaches include organizing the code and giving variables and functions descriptive names.

Using comments is another way to improve the readability of your code. A comment is an explanation or annotation in human-readable form that is used to explain the code. If you wrote a complex regex, for example, you would include a comment describing what the code does.

When you look at your Python code in the future, adding comments will save you a lot of time and effort. Assume you want to change a script you wrote months or years ago. Unless you add a comment, you're unlikely to remember why you wrote a complicated piece of code. The comments also assist other developers in comprehending your code and its purpose.

Comments must be brief and to the point. Do not explain something that the reader already knows.

In this tutorial, we will discuss the fundamentals of writing comments in Python. We will also address a few FAQs on fundamentals of writing comments in Python.

Writing Comments in Python

Python disregards anything written after the hash mark (#).

Comments can be placed at the start of a line or inline with other code:

# This is a Python comment.
print("Hello World") # This is an inline Python comment.

The blank space after the hash mark is optional, but it improves the readability of the comment.

A hash character within a string literal does not represent the beginning of a comment line. It's just a hash character:

paragraph = "# Hash inside quotes is not a comment."

Comments should be at the same indent level as the code beneath it:

```py
def factorial(n):
  if n == 0:
    return 1
  else:
    # Use the factorial function
    return n * factorial(n-1)

Comments are usually represented in green if your text editor supports syntax highlighting.

When debugging a script, comments are also useful. You can comment out some lines or blocks instead of deleting them:

# for fruit in fruits:
#   print(fruit)

Multiline Comments in Python (Comment Blocks)

Python, unlike other popular programming languages, only supports single-line comments.

To write multiline comments in Python, simply add single line comments one after the other:

# This is the first line.
# This is the second line.

Another possibility is to use docstrings.

Docstrings are multiline string literals that are used to describe the functionality of a module, function, class, or method.

A docstring is a string that begins and ends with triple double quotes (""") and can span one or more lines:

"""This is
a multiline
docstring.
"""

Docstrings are not, technically, comments. When a docstring appears as the first statement in a module, function, class, or method, it is parsed into bytecode and becomes the object's __doc__ special attribute. You should use standard single-line hash comments instead.

Shebang

You may have noticed that some Python scripts begin their first line with the characters #! and the path to the Python interpreter:

#!/usr/bin/env python3

This string of characters is known as the shebang, and it instructs the operating system which interpreter to use to parse the rest of the file. Scripts that begin with shebang and are executable can be run in the terminal without first typing python.

Because the shebang line begins with the hash character, the Python interpreter treats it as a comment and ignores it.

FAQs to Fundamentals of Writing Comments in Python

How do I write a single-line comment in Python? 

To write a single-line comment, begin the line with a hash symbol (#), followed by the comment text. Example: # This is a single-line comment.

Can I write multi-line comments in Python? 

Yes, for multi-line comments, you can enclose the comment text between triple quotes (""" or '''). This is often referred to as a docstring, which can span multiple lines.

Why should I write comments in my Python code?

Comments improve code understandability and maintainability. They provide explanations, documentations, and insights into the purpose, functionality, or complex parts of the code.

Should I comment every line of my Python code? 

Commenting every line is not necessary and can make the code cluttered. Focus on commenting sections that require clarification, logic explanations, or areas that may be challenging to understand.

What should I include in my comments? 

Comments should include information that aids comprehension, such as the purpose of functions, important variables, algorithm explanations, assumptions, or potential caveats.

Can comments improve collaboration among developers? 

Yes, comments enhance collaboration as they allow other developers to understand your code better. Clear and concise comments can facilitate code reviews, troubleshooting, and collaboration on shared projects.

Are comments considered during program execution? 

No, comments are completely ignored by the Python interpreter and have no impact on the program's functionality or performance.

Conclusion

Writing comments is a good practice because it assists other developers, including your future self, in understanding what the code does. Everything after the hash mark (#) and until the end of the line is considered a comment in Python.

If you have any queries, please leave a comment below, and we’ll be happy to respond to them.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.