By Dungeon Hunter


2011-10-08 12:51:13 8 Comments

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?

23 comments

@Nematillo Ochilov 2020-09-08 15:44:31

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
"""

@Georgy 2020-09-08 16:02:37

The first two advice seem to be coming from PEP 8. Note that for multiline comments PEP 8 tells us to construct them from consecutive single-line comments, not as multiline strings: python.org/dev/peps/pep-0008/#block-comments.

@jojo 2019-09-29 17:38:49

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

@merin 2020-01-21 18:09:53

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__

@Peter Mortensen 2020-02-03 17:53:41

"DockString"? Do you have a reference?

@merin 2020-02-04 04:51:25

@aniltilanthe 2019-11-07 14:32:13

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!
# =============================================================================

@Rajkamal Mishra 2019-06-11 12:41:43

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.

@Tarjeet Singh 2019-01-22 11:04:29

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 + #.

@Madan Sapkota 2018-12-15 04:26:42

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.
'''

@YouKnowWhoIAm 2018-12-10 09:20:17

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.

@RATAN KUMAR 2018-10-06 12:09:05

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

@Viraj Wadate 2018-08-30 08:41:40

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)

@d.nedelchev 2018-06-27 14:44:20

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,'

@alpha_989 2018-01-31 18:16:10

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 #.

@unutbu 2011-10-08 12:54:52

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! :-)

@Varun Bhatia 2013-06-24 06:53:13

triple quoted string (''') indeed work to fulfil multi line comments.

@Saurav Kumar 2013-12-11 06:53:17

Thanks.. Used (''') and (""") to comment out the block but it didn't help me for Django applications. So chose IDLE and there are options like Comment out region and Uncomment regions (shortcut: Alt+3 and Alt+4 respectively) under Format menu. Now it is more easier than ever..

@Sbspider 2014-04-11 02:42:23

You should also consider using a IDE. Yes, they are hefty, but if used properly they can really boost coding time. I personally used to use PyDev, and now use PTVS (with visual studio). I would definitely reccomend PTVS, as it is really nice to work with, containing the above features along with a lot more - direct integration with virtualenvs, and really good debugging, to say the least

@unutbu 2015-07-18 09:28:47

@ADTC: In acknowledgment of Petr Viktorin's answer, I edited my answer to read "Python does have a multiline string/comment syntax".

@ADTC 2015-07-18 10:31:04

@HappyLeapSecond I think you should clarify it saying "Python doesn't have a true multiline comment syntax, but supports multiline strings that can be used as comments."

@Albert Godfrind 2016-02-26 17:01:20

What I want is an easy way to comment out whole blocks of code when testing. Other languages make that easy. Python is just a pain.

@quemeful 2016-10-20 21:16:13

the benefit of multiline comments when developing is helpful when some of the lines in the area are commented and you don't want to confuse them with the good lines of code

@Bachsau 2018-10-22 10:23:15

I would still consider it bad style, even though Guido says it's ok. Not suitable for releases, but a quick and dirty solution while testing and debugging. Another way to keep around old code while edition a function is to just put return command above it.

@Kevin 2019-04-27 04:41:12

"you would be right to say it is not guaranteed as part of the language specification." - Bytecode is not guaranteed as part of the language specification. The implementation is free to interpret Python code line for line as text, AOT compile it into machine code, or whatever it wants, without necessarily creating bytecode at all. So it's rather strange to pick one very specific implementation detail and call it out in this fashion.

@Petr Viktorin 2011-10-08 12:58:47

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

'''
This is a multiline
comment.
'''

(Make sure to indent the leading ''' appropriately to avoid an IndentationError.)

Guido van Rossum (creator of Python) tweeted this as a "pro tip".

However, Python's style guide, PEP8, favors using consecutive single-line comments, and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.

@unutbu 2011-10-08 13:18:16

Hm. I put a huge multiline string in a python script test.py just to see. When I do import test, a test.pyc file is generated. Unfortunately, the pyc file is huge and contains the entire string as plain text. Am I misunderstanding something, or is this tweet incorrect?

@Petr Viktorin 2011-10-08 13:21:09

@unutbu, if it was the only thing in the file, it was a docstring. Put some code before it and it'll disappear from the pyc. I edited the answer and put „module“ to the list of things that have docstrings.

@Sven Marnach 2011-10-08 13:31:06

I don't like multiline string as comments. Syntax highlighting marks them as strings, not as comments. I like to use a decent editor that automatically deals with commenting out regions and wrapping multiline comments while I type. Of course, it's a matter of taste.

@Petr Viktorin 2011-10-08 13:48:11

@Sven, my editor happens to mark them as comments, unless used in an expression. Maybe you could (open a request to) fix the syntax highlighting for your editor? Python does ignore these, so they are comments. But yes, it's a matter of taste.

@Voo 2011-10-08 14:30:36

While my editor highlights them correctly, I agree that just using ctrl-something to comment/uncomment several lines is simpler and looks better in my opinion (but then I'm also not using /* */ in Java, C# or c++). Just a matter of taste I assume ;)

@Roshambo 2012-12-18 20:03:58

As a convention I find it helpful to use """ for docstrings and ''' for block comments. In this manner you can wrap ''' around your usual docstrings without conflict.

@emmagras 2013-01-10 22:02:43

Though not optimally space efficient, I use ''' when I only want a small comment in a line of code.

@Air 2014-05-21 19:32:00

While you can use multi-line strings as multi-line comments, I'm surprised that none of these answers refer to the PEP 8 subsection that specifically recommends constructing multi-line comments from consecutive single-line comments, with blank # lines to distinguish paragraphs.

@Petr Viktorin 2014-05-26 14:34:04

@AirThomas: Yeah, I agree. Not terribly sure if it's fair to change a 200+ answer from "Use this, it's great and BDFL-blessed" to "You can use this, but it's not something you'd want to commit to the repo", but I went ahead and made the change.

@DevPlayer 2014-09-10 13:27:30

Additionally whether you use triple-apostrophes, triple-quotation marks or hash/pound comment tokens may depend if you use any third party source code tools that clean up or create document generators that pull text from the source.

@continuousqa 2014-09-23 17:43:27

I would be cautious about using triple quotes. In Python 2 it seems fine, but I have found libraries that throw errors in Python 3, when \N is in the triple quotes...as it's read like a doc string. Here's an example: ''' (i.e. \Device\NPF_..) ''' That will result in an error as it reads \N and no longer acts like a true comment, but interprets what is in there. Which makes me wonder if compiling is also interpreting the triple quotes... which a real comment shouldn't be considered at compile time, right?

@Petr Viktorin 2014-09-24 14:57:12

Yes, \N introduces a named Unicode character (try "\N{BLACK STAR}" in Python 3). It does the same thing in Python 2 Unicode strings as well. You'll have the same problem with \x, \u, and \U.

@Eyal 2015-03-30 14:17:05

If your comment includes a long piece of text that you'd like to be able to copy-paste, either you have to put it all on one line or use block comments. Another vote for block comments.

@Demis 2015-06-09 18:33:41

fyi, using string-literals (single or tripe-quotes) for comments can lead to strange problems. For example, I recently got an Indentation Error... which I finally figured out was due to there being a triple-quoted '''comment''' right before an elif statement. Since the '''string-literal''' is actually just code that does nothing (not a comment) it does affect indentations.

@unutbu 2015-07-18 12:03:21

@PetrViktorin: The tweet link seems to have changed to twitter.com/gvanrossum/status/112670605505077248. Would you please put the actual text in your answer to protect against link decay?

@Petr Viktorin 2015-07-18 13:35:45

@HappyLeapSecond: Thanks, I corrected the link. But the tweet is already paraphrased in the answer; copying it wouldn't bring anything new.

@jshepherd 2016-10-06 07:55:37

I am allways amazzed about Python's simplicity. Comment are strings in the source code. So comments interpreted by the interpreter as strings, but they are forgotten by the interpreter in the same CPU click as the reference counter of the object is 0. So we needn't any precompiler or soficticated IDE to handle the multiline comments.

@DeeJayh 2018-01-16 02:28:01

Using ''' to multi-line comment is terrible procedure as it is not ignored by the interpreter like an actual comment is. It is garbage-collected instantly, but the code is still using resources.

@Hack-R 2018-02-03 15:46:07

I have to say this is an extremely poor choice of syntax (the fault of the Python devs, not you). Why? If for not for the many reasons in other comments because most IDE's including Jupyter automatically give you 2 single quotes instead of 1, thus getting 3 is a pain. Yet it would not be worth it to change the behavior. The syntax should just be like the many other more sensible choices out there including /* */.

@Petr Viktorin 2018-02-04 10:00:35

If you're using an IDE, use its “comment” shortcut – e.g. Ctrl+/ in Jupyter. (And yes, Jupyter automatically adding stuff I didn't actually type drives me up the wall.)

@Prof Mo 2018-02-22 16:26:32

This answer is incorrect. multiline strings are not the same as a comment. A comment is whitespace and has no semantic interpretation. However, a multiline comment does.

@Bob Stein 2018-07-16 13:24:07

@Roshambo I use your convention, and more: '''block comment''' instead of pass. I find this helpful to explain an empty except-clause or if-else-clause.

@riha 2019-06-13 14:38:34

Btw, the whole multiline string can be toggled "on/off" by putting a single # before the closing '''. Now, if you put another # before the opening ''', the whole section will be code. If you remove the first # again, it will be back to multiline string. Really helpful to temporarily disable several/lots of lines of code easily (unless they contain ''' multiline strings, of course). But then again, you could use double-quotes for your toggle.

@Ardent 2020-02-09 22:08:59

I am getting an indentation error. I did indent the apostrophes correctly. Could you please help me out? is it necessary to indent the apostrophes just like the previous line? Or can I start it from the start of the new physical line?

@javadba 2020-09-19 17:06:35

Pep8 recommending multi-line strings is yet another big fail on that spec. It's one of the worst things for a language already having major issues. In an age of 3K laptops: 79-character lines (which much of that taken up by the 4-space indentations) anyone??

@Petr Viktorin 2020-09-21 07:28:19

@javadba PEP 8 does not recommend multi-line strings for comments. Also, PEP 8 explicitly says you can agree on a different line length. (Myself, I like to have several files open side-by-side on the big screen, and also see the whole line on a phone.)

@javadba 2020-09-21 10:36:02

@PetrViktorin Thx for pointing that out! There are many users of PEP8 that are not aware of that option to use the 99 length.

@Edison 2019-08-29 04:01:03

Visual Studio Code universal official multi-line comment toggle.

macOS: Select code-block and then +/

Windows: Select code-block and then Ctrl+/

@SomeAnonymousPerson 2015-02-16 14:00:30

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
   """

@Demis 2015-06-09 18:35:36

triple-quotes are a way to insert text that doesn't do anything (I believe you could do this with regular single-quoted strings too), but they aren't comments - the interpreter does actually execute the line (but the line doesn't do anything). That's why the indentation of a triple-quoted 'comment' is important.

@Ken Williams 2017-03-01 19:16:22

This solution is incorrect, the weather2 comment is actually a docstring since it's the first thing in the class.

@alpha_989 2018-02-02 03:47:57

Agree with @KenWilliams. This is not a correct solution. Try putting this in the middle of a function/class, and see how it messes up your formatting and automating code folding/linting.

@shafik 2019-07-08 03:34:17

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__

@Peter Mortensen 2020-02-03 17:34:35

What does this add over the previous answers?

@shafik 2020-02-04 03:06:38

My answer contains more details, which may help developer more.

@0m3r 2019-03-14 07:53:08

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.")

@K_holla 2017-09-15 05:27:03

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 #.

@A.G 2017-05-11 15:47:53

On Python 2.7.13:

Single:

"A sample single line comment "

Multiline:

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

@mcalex 2017-07-09 01:59:06

You're saying single quotes create a comment in python 2.7?

@johanno 2017-09-22 20:43:16

Using a single set of quotes creates a string. A single line comment should be prefixed with a #.

@Aya 2016-06-29 13:04:14

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()

@GingerPlusPlus 2016-06-29 14:13:16

Then, you can use r'raw string' -- r'\xor' == '\\xor'.

@user1919238 2016-07-27 09:31:40

Well, any "true" multi-line comment must also be parsed and syntactically valid. C-style comments can't contain a */ as it will terminate the block, for example.

@el.pescado 2016-09-29 05:50:56

@dan1111 that's obvious that comment cannot include end marker, but that's the only limitation.

@el.pescado 2016-09-29 05:55:10

''' "comments" have more limitations. You can only comment out whole statements, whereas comments can comment out parts of expression. Example: In C, you can comment out some list elements: int a[] = {1, 2, /* 3, 4, */ 5};. With Multi line string, you can't do that, as that would put a string inside your list.

@Sanjay T. Sharma 2011-10-08 12:55:01

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.

@Fernando Gonzalez Sanchez 2015-02-23 16:54:06

this is incorrect, see the responses on using triple quotes.

@Sanjay T. Sharma 2015-02-23 20:40:29

@FernandoGonzalezSanchez: It's really not incorrect. This "multi-line string as comment" can be best described as a "pro-tip". The official Python docs say nothing on this, hence the question posted by OP.

@Sanjay T. Sharma 2015-02-24 10:55:07

That's a PEP for docstrings; there isn't a single mention of "comment" on that page.

@Anti Earth 2011-10-08 12:54:46

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.

Related Questions

Sponsored Content

53 Answered Questions

[SOLVED] Can comments be used in JSON?

  • 2008-10-28 20:39:03
  • Michael Gundlach
  • 2429793 View
  • 7851 Score
  • 53 Answer
  • Tags:   json comments

22 Answered Questions

[SOLVED] What are metaclasses in Python?

62 Answered Questions

[SOLVED] How to call an external command?

26 Answered Questions

[SOLVED] How can I safely create a nested directory?

31 Answered Questions

[SOLVED] "Least Astonishment" and the Mutable Default Argument

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

46 Answered Questions

[SOLVED] What's a quick way to comment/uncomment lines in Vim?

  • 2009-11-04 21:06:32
  • Ethan
  • 937391 View
  • 1220 Score
  • 46 Answer
  • Tags:   vim comments

23 Answered Questions

[SOLVED] Is there a way to run Python on Android?

26 Answered Questions

[SOLVED] Pythonic way to create a long multi-line string

Sponsored Content