Search code examples
pythonsyntaxcomments

why python allows triple quotes both as multi-line comment as well as string literal


I am new to python and question may sound silly but I wanted to clear it. While learning I came across code where python is allowing triple quotes(""") both as multi-line comment and also as string literal. So how does python knows if it is intended as comment or a string literal.

"""This
is treated
as comment
and ignored"""

a = """It is
treated as
string literal"""
print(a)

Output:-

It is
treated as
string literal

Solution

  • Essentially, if the triple quotation marks aren’t assigned to a variable or a doc string, python will ignore it. For example

    """"This is a module-level docstring""""
    
    
    def randomFunction():
       """This will be treated as a docstring,
       so if you were to run help(randomFunction) it 
       will display whatever is in here"""
    
    
       a = """This is actually assigned to a variable,
       and thus python will interpret it as such"""
    
       """This by itself is just an unassigned string variable """
    

    The same happens with strings, which are inside two quotes.