ChatGPT解决这个技术问题 Extra ChatGPT

How do I create multiline comments in Python?

How do I make multi-line comments? Most languages have block comment symbols like:

/*

*/
I suppose being an interpreted language, it makes sense, as in the case of sh or bash or zsh, that # is the only way to make comments. I'm guessing that it makes it easier to interpret Python scripts this way.
I know this answer is old, but I came across it because I had the same question. The accepted answer DOES work, though I don't know enough of Python to know the intricacies of why it may not be correct (per ADTC).
@BrandonBarney Let me explain you the issue. The accepted answer, which uses ''', actually creates a multi-line string that does nothing. Technically, that's not a comment. For example, you can write k = '''fake comment, real string'''. Then, print(k) to see what ADTC means.
That makes so much more sense now. I'm used to vba where creating an unused string results in an error. I didn't realize python just ignores it. It still works for debugging and learning at least, but isn't good practice for actual development.
In Python source code, if you break a long line, the editor automatically indents it, to show that the broken line is really part of the previous line? Is that what I should do if I break up a long line of pseudocode?

l
larsks

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, like this:

# This is a multiline
# comment.

...and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.


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?
@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.
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.
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.
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.
P
Peter Mortensen

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


triple quoted string (''') indeed work to fulfil multi line comments.
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..
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
@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."
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.
A
Aya

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

Then, you can use r'raw string' -- r'\xor' == '\\xor'.
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.
@dan1111 that's obvious that comment cannot include end marker, but that's the only limitation.
''' "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.
n
ncica

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

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.
This solution is incorrect, the weather2 comment is actually a docstring since it's the first thing in the class.
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.
C
Community

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.


this is incorrect, see the responses on using triple quotes.
@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.
That's a PEP for docstrings; there isn't a single mention of "comment" on that page.
P
Peter Mortensen

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.


P
Peter Mortensen

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


this should be the accepted answer
P
Peter Mortensen

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


E
Edison

Visual Studio Code universal official multi-line comment toggle. Similar to Xcode shortcut.

macOS: Select code-block and then ⌘+/

Windows: Select code-block and then Ctrl+/


P
Peter Mortensen

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

j
jojo

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

P
Peter Mortensen

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


P
Peter Mortensen

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)

P
Peter Mortensen

On Python 2.7.13:

Single:

"A sample single line comment "

Multiline:

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

You're saying single quotes create a comment in python 2.7?
Using a single set of quotes creates a string. A single line comment should be prefixed with a #.
P
Peter Mortensen

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

G
Georgy

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

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.
0
0m3r

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

P
Peter Mortensen

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.


P
Peter Mortensen

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

s
shafik

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__

What does this add over the previous answers?
My answer contains more details, which may help developer more.
P
Peter Mortensen

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.


P
Peter Mortensen

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


P
Peter Mortensen

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__

"DockString"? Do you have a reference?
m
me1234

Yes, you can simply use

'''
Multiline!
(?)
'''

or

"""
Hello
World!
"""

BONUS: It's a little bit harder, but it's safer to use in older versions, print functions or GUIs:

# This is also
# a multiline comment.

For this one, you can select the text you want to comment and press Ctrl / (or /), in PyCharm and VS Code.

But you can edit them. For example, you can change the shortcut from Ctrl / to Ctrl Shift C.

WARNING!

Be careful, don't overwrite other shortcuts! Comments have to be correctly indented!

Hope this answer helped. Good luck next time when you'll write other answers!