Python Multi-line Comments with Examples

Posted in /   /  

Python Multi-line Comments with Examples
vinaykhatri

Vinay Khatri
Last updated on April 18, 2024

    In programming languages, we use comments to provide additional information about the source code. So if some other developer reads your code or you get back to your code after a long time, the comments tell us what a specific block of code is supposed to do. Generally, we use comments to provide alternative information about the code snippet, but they also help in debugging code. If we comment out a part of code in Python, then the python interpreter will not execute that part of the code.

    Python Multi-line Comments

    To write a multi-line comment in Python, we can use triple double-inverted(""" Comment """) or single-inverted(''' Comment ''') quotes.

    Example

    def add(a,b):
        '''
         This is a user defined
         function to add two numbers
        '''
       return a+b
    
    a= 200
    b= 300
    
    print(add(a,b))

    Output

    500

    Note: While writing the multi-line comments, make sure that you do not write them at the right side of the assignment operator (=) because we use triple double-inverted and single-inverted quotations for multi-line strings.

    Example

    s ='''This is not a comment
    it is a string'''
    
    print(s)

    Output

    This is not a comment
    it is a string

    Python Single Line Comment

    We use the hash symbol(#) to write single-line comments in Python. Single line comments

    def add(a,b):
        #This is a user defined
        #function to add two numbers
        return a+b
    
    a= 200
    b= 300
    
    print(add(a,b))

    To Sum it Up

    Comments play a crucial role in our source code or program. It makes code readable and specifies what a particular code block is supposed to do when executed. To write a multi-line comment in Python, we use triple single-inverted and double-inverted quotes. However, it is better to use consecutive single-line comments for adding multi-line comments. The sole reason behind this is that we also use the double-inverted triple quotation for multi-line strings. Hopefully, this article has helped you understand how to write multi-line comments in Python. If you have any queries regarding this topic, you can share them with us in the comments section below.

    People are also reading:

    Leave a Comment on this Post

    0 Comments