Python multiline comments - python

I am struggling with multi line comments in Python, I understood I can use # at the start of every line of multi line comments but there is also another way of using """ at the start and end of the comment; however, in my interpreter the """ method gives an output instead of ignoring the comment.
>>> """this should
be a multi
line comment"""
And my interpreter gives the following output:
'this should\nbe a multi\nline comment'
Can someone explain it?

Triple quoted strings are used as comments by many developers but it is actually not a comment. It is similar to regular strings in python but it allows the string to be multi-line. You will find no official reference for triple quoted strings to be a comment.
In python, there is only one type of comment that starts with hash # and can contain only a single line of text.
According to PEP 257, it can however be used as a docstring, which is again not really a comment.
def foo():
"""
Developer friendly text for describing the purpose of function
Some test cases used by different unit testing libraries
"""
<body of the function>
You can just assign them to a variable as you do with single quoted strings:
x = """a multi-line text
enclosed by
triple quotes
"""
Furthermore, if you try it in a repl, triple quoted strings get printed, had it really been a comment, should it have been printed?:
>>> #comment
>>> """triple quoted"""
'triple quoted'

This is very easy to accomplish in python.
# This is a single-line comment
'''
This is a multi-line comment
'''
Just put the comments in ''' and put whatever you want inside of them!

Related

Is there any way to make a multi-line comment in Python? [duplicate]

How do I make multi-line comments? Most languages have block comment symbols like:
/*
*/
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.
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! :-)
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()
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
"""
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.
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
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.
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 #.
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+/
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,'
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
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 #.
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)
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
"""
On Python 2.7.13:
Single:
"A sample single line comment "
Multiline:
"""
A sample
multiline comment
on PyCharm
"""
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.
'''
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.")
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.
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!
# =============================================================================
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!
This can be done in Vim text editor.
Go to the beginning of the first line in the comment area.
Press Ctrl+V to enter the visual mode.
Use arrow keys to select all the lines to be commented.
Press Shift+I.
Press # (or Shift+3).
Press Esc.
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__
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.
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 + #.
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__
in windows: you can also select the text or code chunks and press ctr + / and do the same if you want to remove the comments.
in mac: it should be comment + /
I read about all of the drawbacks of the various ways of doing this, and I came up with this way, in an attempt to check all the boxes:
block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
def __init__(self):
# create the event object inside raising class
self.on_thing_happening = Event()
def doing_something(self):
# raise the event inside the raising class
self.on_thing_happening()
class ExampleEventHandlingClass():
def __init__(self):
self.event_generating_thing = ExampleEventSource()
# add event handler in consuming class
event_generating_thing.on_thing_happening += my_event_handler
def my_event_handler(self):
print('handle the event')
]#'''
class Event():
def __init__(self):
self.__eventhandlers = []
def __iadd__(self, handler):
self.__eventhandlers.append(handler)
return self
def __isub__(self, handler):
self.__eventhandlers.remove(handler)
return self
def __call__(self, *args, **keywargs):
for eventhandler in self.__eventhandlers:
eventhandler(*args, **keywargs)
Pros
It is obvious to any other programmer this is a comment. It's self-descriptive.
It compiles
It doesn't show up as a doc comment in help()
It can be at the top of the module if desired
It can be automated with a macro.
[The comment] is not part of the code. It doesn't end up in the pyc. (Except the one line of code that enables pros #1 and #4)
If multi-line comment syntax was ever added to Python, the code files could be fixed with find and replace. Simply using ''' doesn't have this advantage.
Cons
It's hard to remember. It's a lot of typing. This con can be eliminated with a macro.
It might confuse newbies into thinking this is the only way to do block comments. That can be a pro, just depends on your perspective. It might make newbies think the line of code is magically connected to the comment "working".
It doesn't colorize as a comment. But then again, none of the answers that actually address the spirit of the OP's question would.
It's not the official way, so Pylint might complain about it. I don't know. Maybe; maybe not.
Here's an attempt at the VS Code macro, although I haven't tested it yet:
{
"key": "ctrl+shift+/",
"command": "editor.action.insertSnippet",
"when": "editorHasSelection"
"args": {
"snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
}
}

"""Different""", "quote", 'types' in function?

I am trying to figure out if the different quote types make a difference functionally. I have seen people say its preference for "" or '' but what about """ """? I tested it in a simple code to see if it would work and it does. I was wondering if """ triple quotes """ have a functional purpose for defined function arguments or is it just another quote option that can be used interchangeably like "" and ''?
As I have seen many people post about "" and '' I have not seen a post about """ """ or ''' ''' being used in functions.
My question is: Does the triple quote have a unique use as an argument or is it simply interchangeable with "" and ''? The reason I think it might have a unique function is because it is a multi line quote and I was wondering if it would allow a multi line argument to be submitted. I am not sure if something like that would even be useful but it could be.
Here is an example that prints out what you would expect using all the quote types I know of.
def myFun(var1="""different""",var2="quote",var3='types'):
return var1, var2, var3
print (myFun('All','''for''','one!'))
Result:
('All', 'for', 'one!')
EDIT:
After some more testing of the triple quote I did find some variation in how it works using return vs printing in the function.
def myFun(var1="""different""",var2="""quote""",var3='types'):
return (var1, var2, var3)
print(myFun('This',
'''Can
Be
Multi''',
'line!'))
Result:
('This', 'Can\nBe\nMulti', 'line!')
Or:
def myFun(var1="""different""",var2="""quote""",var3='types'):
print (var1, var2, var3)
myFun('This',
'''Can
Be
Multi''',
'line!')
Result:
This Can
Be
Multi line!
From the docs:
String literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). [...other rules applying identically to all string literal types omitted...]
In triple-quoted strings, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the string. (A “quote” is the character used to open the string, i.e. either ' or ".)
Thus, triple-quoted string literals can span multiple lines, and can contain literal quotes without use of escape sequences, but are otherwise exactly identical to string literals expressed with other quoting types (including those using escape sequences such as \n or \' to express the same content).
Also see the Python 3 documentation: Bytes and String Literals -- which expresses an effectively identical set of rules with slightly different verbiage.
A more gentle introduction is also available in the language tutorial, which explicitly introduces triple-quotes as a way to permit strings to span multiple lines:
String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
produces the following output (note that the initial newline is not included):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
To be clear, though: These are different syntax, but the string literals they create are indistinguishable from each other. That is to say, given the following code:
s1 = '''foo
'bar'
baz
'''
s2 = 'foo\n\'bar\'\nbaz\n'
there's no possible way to tell s1 and s2 apart from each other by looking at their values: s1 == s2 is true, and so is repr(s1) == repr(s2). The Python interpreter is even allowed to intern them to the same value, so it may (or may not) make id(s1) == id(s2) true depending on details (such as whether the code was run at the REPL or imported as a module).
FWIW, my understanding is that there's a convention whereby """ """, ''' ''' are used for docstring, which is kinda like a #comment, but is a recallable attribute that can be referenced later. https://www.python.org/dev/peps/pep-0257/
I'm a beginner too, but my understanding is that using triple quotes for strings is not the best idea, even if there's little functional difference with what you're doing currently (I don't know if there might be later). Sticking with conventions is helpful to others reading and using your code, and it seems to be a good rule of thumb that some conventions will bite you if you don't follow them, as in this case where a mal-formatted string with triple quotes will be interpreted as a docstring, and maybe not throw an error, and you'll need to search through a bunch of code to find the issue.

What is the difference between multi-line comment and multi-line string in python? [duplicate]

This question already has answers here:
Python comments: # vs. strings
(3 answers)
Closed 6 years ago.
I am still exploring python. Today I came across multi-line strings. If I do:
a = '''
some-text
'''
The content of variable a is '\nsome-text\n'. But this leaves me confused. I always thought that if you enclose something within three single quotes ('''), you are commenting it out. So the above statement would be equivalent to something like this in C++:
a = /*
some-text
*/
What am I missing?
Technically such multi-line-comments enclosed in triple quotes are not really comments but string literals.
The reason why you can still use them to comment stuff out is that a string literal itself does not represent any kind of operation. It gets parsed, but nothing is done with it and it does not get assigned to a variable name, so it gets ignored.
You could also place any other literal into your code. As long as it is not involved in any kind of operation or assignment, it gets basically ignored like a comment. It is not a comment though, just useless code if you want to name it that way.
Here's an example of code that does... well, nothing:
# This is a real comment.
"useless normal string"
"""useless triple-quoted
multi-line
string"""
[1, "two"] # <-- useless list
42 # <-- useless number
I always thought that if you enclose something within three single quotes (''')
This is not the case, actually. Enclosing something in triple quotes '''string''', it creates a string expression which yields a string containing the characters within the quotes. The difference between this and a single quoted string 'string' is that the former can be on multiple lines. People often use this to comment out multiple lines.
However, if you don't assign the string expression to a variable, then you'll get something a lot like a comment.
'''this is
a useless piece of python
text that does nothing for
your program'''
In python, wrapping your code with ''' will encode it as a string, effectively commenting it out unless that code already contains a multi-line string literal ''' anywhere. Then, the string will be terminated.
print('''hello!
How are you?''')
# this will not have the intended comment effect
'''
print('''hello!
How are you?''')
'''

Ending a comment in Python

I have already read this: Why doesn't Python have multiline comments?
So in my IDLE , I wrote a comment:
Hello#World
Anything after the d of world is also a part of the comment.In c++ , I am aware of a way to close the comment like:
/*Mycomment*/
Is there a way to end a comment in Python?
NOTE: I would not prefer not to use the triple quotes.
You've already read there are no multiline comments, only single line. Comments cause Python to ignore everything until the end of the line. You "close" them with a newline!
I don't particularly like it, but some people use multiline strings as comments. Since you're just throwing away the value, you can approximate a comment this way. The only time it's really doing anything is when it's the first line in a function or class block, in which case it is treated as a docstring.
Also, this may be more of a shell scripting convention, but what's so bad about using multiple single line comments?
#####################################################################
# It is perfectly fine and natural to write "multi-line" comments #
# using multiple single line comments. Some people even draw boxes #
# with them! #
#####################################################################
You can't close a comment in python other than by ending the line.
There are number of things you can do to provide a comment in the middle of an expression or statement, if that's really what you want to do.
First, with functions you annotate arguments -- an annotation can be anything:
def func(arg0: "arg0 should be a str or int", arg1: (tuple, list)):
...
If you start an expression with ( the expression continues beyond newlines until a matching ) is encountered. Thus
assert (
str
# some comment
.
# another comment
join
) == str.join
You can emulate comments by using strings. They are not exactly comments, since they execute, but they don't return anything.
print("Hello", end = " ");"Comment";print("World!")
if you start with triple quotes, end with triple quotes

How do I create multiline comments in Python?

How do I make multi-line comments? Most languages have block comment symbols like:
/*
*/
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.
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! :-)
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()
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
"""
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.
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
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.
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 #.
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+/
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,'
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
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 #.
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)
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
"""
On Python 2.7.13:
Single:
"A sample single line comment "
Multiline:
"""
A sample
multiline comment
on PyCharm
"""
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.
'''
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.")
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.
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!
# =============================================================================
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!
This can be done in Vim text editor.
Go to the beginning of the first line in the comment area.
Press Ctrl+V to enter the visual mode.
Use arrow keys to select all the lines to be commented.
Press Shift+I.
Press # (or Shift+3).
Press Esc.
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__
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.
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 + #.
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__
in windows: you can also select the text or code chunks and press ctr + / and do the same if you want to remove the comments.
in mac: it should be comment + /
I read about all of the drawbacks of the various ways of doing this, and I came up with this way, in an attempt to check all the boxes:
block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
def __init__(self):
# create the event object inside raising class
self.on_thing_happening = Event()
def doing_something(self):
# raise the event inside the raising class
self.on_thing_happening()
class ExampleEventHandlingClass():
def __init__(self):
self.event_generating_thing = ExampleEventSource()
# add event handler in consuming class
event_generating_thing.on_thing_happening += my_event_handler
def my_event_handler(self):
print('handle the event')
]#'''
class Event():
def __init__(self):
self.__eventhandlers = []
def __iadd__(self, handler):
self.__eventhandlers.append(handler)
return self
def __isub__(self, handler):
self.__eventhandlers.remove(handler)
return self
def __call__(self, *args, **keywargs):
for eventhandler in self.__eventhandlers:
eventhandler(*args, **keywargs)
Pros
It is obvious to any other programmer this is a comment. It's self-descriptive.
It compiles
It doesn't show up as a doc comment in help()
It can be at the top of the module if desired
It can be automated with a macro.
[The comment] is not part of the code. It doesn't end up in the pyc. (Except the one line of code that enables pros #1 and #4)
If multi-line comment syntax was ever added to Python, the code files could be fixed with find and replace. Simply using ''' doesn't have this advantage.
Cons
It's hard to remember. It's a lot of typing. This con can be eliminated with a macro.
It might confuse newbies into thinking this is the only way to do block comments. That can be a pro, just depends on your perspective. It might make newbies think the line of code is magically connected to the comment "working".
It doesn't colorize as a comment. But then again, none of the answers that actually address the spirit of the OP's question would.
It's not the official way, so Pylint might complain about it. I don't know. Maybe; maybe not.
Here's an attempt at the VS Code macro, although I haven't tested it yet:
{
"key": "ctrl+shift+/",
"command": "editor.action.insertSnippet",
"when": "editorHasSelection"
"args": {
"snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
}
}

Categories