TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Write Multiline Comments in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

How to Write Multiline Comments in Python

Last updated: Nov 28, 2023 11:14 pm
By Harsh S.
Share
9 Min Read
Write Multiline Comments in Python
SHARE

In Python, there is no specific syntax for creating multiline comments like some other programming languages (e.g., C, C++, Java). Instead, Python relies on other methods to achieve similar goals. Multiline comments are typically used to provide explanations, documentation, or notes within your code.

Contents
Advantages of Multi-Line CommentsMethod#1: Triple-Quoted StringsMethod#2: DocstringsMethod#3: Hash Character (#) for Each LineCompare Methods to Add Multiline Comments in PythonVarious Examples of Multiline Comments in Python

In this tutorial, we will explore various methods for adding multi-line comments in Python, including triple-quoted strings and documentation strings. We will also provide examples and a comparison table to help you choose the most suitable method for your needs.

Must Read: How to Create Multiline Strings in Python?

How do You Comment on Multiple Lines in Python?

Python never officially supported multiline comments through a dedicated syntax. Therefore, there was no built-in way to write multiline comments. Instead, programmers would use a variety of ad-hoc methods to write multiline comments, such as using multiple hash characters (#) or enclosing the comment within triple quotes (”’).

What exactly is a multiline comment?

A multi-line comment is a piece of text overflowing to multiple lines and written to describe what a line of code does. Similar to a one-line comment, it is for informational purposes only and does not execute.

Let’s learn about them more in the next sections. But before that, you can follow some of the benefits of adding a multiline comment in your code.

Advantages of Multi-Line Comments

There are several advantages to using multi-line comments in Python:

  • Improve code readability: It helps to explain complex code and makes it more readable as well as easier to understand.
  • Easy to document: Multi-line comments make code easier to understand, help in finding and fixing issues, and promote teamwork among programmers.
  • Switch off the code: Multi-line comments let you turn off code temporarily for testing and debugging.

Read This: How to Iterate Strings in Python

Method#1: Triple-Quoted Strings

One of the most common ways to write multi-line comments in Python is by using triple-quoted strings. The main purpose of these strings is to render information about functions, classes, or modules. We usually call them docstrings.

Here’s how you can use triple-quoted strings to add multi-line comments:

'''
This is how I can write multiline comments in Python.
It's not a standard way, but it allows me to add
comments as long as I want.
'''

You can also use double quotes for triple-quoted strings:

"""
Can I do it differently?
Yes, you definitely can.
In this example, you can clearly see how I'm doing it.
"""

Check This: How to Split a String in Python

Method#2: Docstrings

We already mentioned Docstrings, but let’s take this in a more detailed manner. They actually serve to document the details of a method, class, or module. They follow a certain flow and intend to provide useful data to developers writing code.

Here’s how you can use docstrings:

def sum_func(x, y):
    """
    This function takes two number, x and y, and adds them.
    Call it in the following manner:
    result = sum_func(11, 17)
    """
    return x + y

In the above example, the docstring provides information about the function’s purpose, its parameters, and how to use it. This is especially useful for creating self-explanatory code.

Method#3: Hash Character (#) for Each Line

If you don’t want to use triple-quoted strings or docstrings, you can create multi-line comments by placing a hash character (#) at the beginning of each line. While this approach is less common for multi-line comments, it can be useful in certain situations:

# This is a multi-line comment created using the '#' character.
# It consists of several lines of comments.
# While not as elegant as triple-quoted strings, it gets the job done.

Also Read: Python Comment vs Multiline Comment

Compare Methods to Add Multiline Comments in Python

To help you decide which method is the most suitable for your needs, let’s compare the three methods for multi-line comments in Python:

MethodEase of UseReadabilityDocumentation
Triple-Quoted StringsEasyGoodLimited
DocstringsModerateExcellentExtensive
Hash Character (#)ModerateFairNone
Various methods to write multiline comments in Python
  • Ease of Use: Triple-quoted strings are the most basic way to use for writing multi-line comments. Hash characters and docstrings require more manual effort.
  • Readability: Docstrings are better in terms of providing detailed info. Triple-quoted strings also offer good readability but are not as refined as docstrings. A hash symbol may make the comments less easy to read or understand.
  • Documentation: Docstrings are a tool for documentation. There are tools like Sphinx which extracts their detail to generate documentation. Triple-quoted strings are also useful for documentation but are not counted as an official practice. Hash characters can fulfill the purpose of adding comments but not a good deal for formal documentation.

Check Out: Several Python Exercises to Practice Python

Various Examples of Multiline Comments in Python

Let’s check out a few more dedicated examples.

  1. Triple-Quoted Strings Example:
'''
This function measures the area of a rect.
You need to provide the length and width as arguments.
Use it like this:
area = calc_area(11, 17)
'''
def calc_area(len, wid):
    return len * wid
  1. Docstrings Example:
def divide(dividend, divisor):
    """
    This function divides the 'dividend' by the 'divisor' and returns the result.

    Parameters:
    dividend (int or float): The number to be divided.
    divisor (int or float): The number by which the dividend is divided.

    Returns:
    float: The result of the division.

    Example:
    result = divide(10, 2)
    """
    if divisor == 0:
        raise ValueError("Division by zero is not allowed.")
    return dividend / divisor
  1. Hash Character (#) for Each Line Example:
# The following code shows how to use a custom sorting algo.
# This algorithm has a time complexity of O(n^2)

def cust_sort(arr):
    # The outer loop iterates through each ele of the list.
    for i in range(len(arr)):
        # The inner loop compares the current ele with the rest of the list.
        for j in range(i + 1, len(arr)):
            # If the current element is greater, swap them.
            if arr[i] > arr[j]:
                arr[i], arr[j] = arr[j], arr[i]

Now, it is up to you to choose the method that best fits your needs, coding standards, and the level of doc needed for your code.

Also Check: How to Print Patterns in Python

Conclusion

While you create large Python programs, it becomes a necessity to add useful comments. After reading the above tutorial, you should be easily able to do it. Here’s a summary to help you make an informed decision:

  • Use Triple-Quoted Strings if you just want a simple way to comment.
  • Use Docstrings if you want to add comments and also want to document.
  • Use the Hash Character (#) when you have to add a short and one-liner comment.

You should always keep in mind that writing clear and concise comments is always useful. The other guys working on the same project later would find it easy to manage. If they have a task to extend the code, they must know what it is doing. The comments make you achieve this.

Happy coding!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Slice a Python String with Examples How to Slice a Python String with Examples
Next Article What is the Directory in Computer Aside from Git Bash GitHub Directory in Computer Aside from Git Bash GitHub

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x