[python] Is there a way to create multiline comments in Python?

I have recently started studying Python, but I couldn't find how to implement multi-line comments. Most languages have block comment symbols like

/*

*/

I tried this in Python, but it throws an error, so this probably is not the correct way. Does Python actually have a multiline comment feature?

This question is related to python comments documentation

The answer is


Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.

I am using Anaconda Spyder and it has:

  • Ctrl + 1 - Comment/uncomment
  • Ctrl + 4 - Comment a block of code
  • Ctrl + 5 - Uncomment a block of code

It would comment/uncomment a single/multi line/s of code with #.

I find it the easiest.

For example, a block comment:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

If you put a comment in

"""
long comment here
"""

in the middle of a script, Python/linters won't recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It's better to use

# Long comment
# here.

If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc. Where Vj selects two lines of code, and gcc comments them out.

If you don’t want to use plugins like the above you can use search and replace like

:.,.+1s/^/# /g

This will replace the first character on the current and next line with #.


Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official documentation to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case, your text editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to a text editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the text editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and it should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.


To protect against link decay, here is the content of Guido van Rossum's tweet:

@BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)


Select the lines that you want to comment and then use Ctrl + ? to comment or uncomment the Python code in the Sublime Text editor.

For single line you can use Shift + #.


There is no such feature as a multi-line comment. # is the only way to comment a single line of code. Many of you answered ''' a comment ''' this as their solution.

It seems to work, but internally ''' in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #.

Check the official documentation here


The inline comments in Python starts with a hash character.

hello = "Hello!" # This is an inline comment
print(hello)

Hello!

Note that a hash character within a string literal is just a hash character.

dial = "Dial #100 to make an emergency call."
print(dial)

Dial #100 to make an emergency call.

A hash character can also be used for single or multiple lines comments.

hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)

Hello

World

Enclose the text with triple double quotes to support docstring.

def say_hello(name):
    """
    This is docstring comment and
    it's support multi line.
    :param name it's your name
    :type name str
    """
    return "Hello " + name + '!'


print(say_hello("John"))

Hello John!

Enclose the text with triple single quotes for block comments.

'''
I don't care the parameters and
docstrings here.
'''

I think it doesn't, except that a multiline string isn't processed. However, most, if not all Python IDEs have a shortkey for 'commenting out' multiple lines of code.


I would advise against using """ for multi line comments!

Here is a simple example to highlight what might be considered an unexpected behavior:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

Now have a look at the output:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.

If you want to comment multiple lines do so according to PEP 8 guidelines:

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

Output:

I am a string
clearly I am also a string

From the accepted answer...

You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored.

This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.

If you try to run this code...

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

You'll get either...

ValueError: invalid \x escape

...on Python 2.x or...

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

...on Python 3.x.

The only way to do multi-line comments which are ignored by the parser is...

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()

Well, you can try this (when running the quoted, the input to the first question should quoted with '):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

Whatever enclosed between """ will be commented.

If you are looking for single-line comments then it's #.


Yes, it is fine to use both:

'''
Comments
'''

and

"""
Comments
"""

But, the only thing you all need to remember while running in an IDE, is you have to 'RUN' the entire file to be accepted as multiple lines codes. Line by line 'RUN' won't work properly and will show an error.


Visual Studio Code universal official multi-line comment toggle.

macOS: Select code-block and then ?+/

Windows: Select code-block and then Ctrl+/


On Python 2.7.13:

Single:

"A sample single line comment "

Multiline:

"""
A sample
multiline comment
on PyCharm
"""

You can use the following. This is called DockString.

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__

AFAIK, Python doesn't have block comments. For commenting individual lines, you can use the # character.

If you are using Notepad++, there is a shortcut for block commenting. I'm sure others like gVim and Emacs have similar features.


Multiline comment in Python:

For me, both ''' and """ worked.

Example:

a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)

Example:

a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)

Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.

Here is an example:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

In Python 2.7 the multiline comment is:

"""
This is a
multilline comment
"""

In case you are inside a class you should tab it properly.

For example:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """

If you write a comment in a line with a code, you must write a comment, leaving 2 spaces before the # sign and 1 space before the # sign

print("Hello World")  # printing

If you write a comment on a new line, you must write a comment, leaving 1 space kn in the # sign

# single line comment

To write comments longer than 1 line, you use 3 quotes

"""
This is a comment
written in
more than just one line
"""

For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:

# This is comment 1
# This is comment 2 
# This is comment 3

For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.

'''
This is
multiline
comment
'''

Also, mention that you can access docstring by a class object like this

myobj.__doc__

Using PyCharm IDE.

You can comment and uncomment lines of code using Ctrl+/. Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts). Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

Select all lines then press Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

A multiline comment doesn't actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.

A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a # in front of every line under the selection. Ctrl + Shift + K is for block uncomment.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to comments

Way to create multiline comments in Bash? Jenkins: Can comments be added to a Jenkinsfile? /** and /* in Java Comments Where is the syntax for TypeScript comments documented? Multiple line comment in Python How do I add comments to package.json for npm install? How to comment multiple lines with space or indent Is there a shortcut to make a block comment in Xcode? How to comment and uncomment blocks of code in the Office VBA Editor Which comment style should I use in batch files?

Examples related to documentation

#pragma mark in Swift? pandas resample documentation Create html documentation for C# code How do I create documentation with Pydoc? Documentation for using JavaScript code inside a PDF file How to document a method with parameter(s)? Is there a way to create multiline comments in Python? What is the standard Python docstring format? Android offline documentation and sample codes What to put in a python module docstring?