English 中文(简体)
我如何在沙尔提出多线评论?
原标题:How do I create multiline comments in Python?

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

/*

*/
最佳回答

你们可以使用三条引证。 当他们不做教导时(在班级/职级/单元中是第一件事),他们就会被忽视。

   
This is a multiline
comment.
   

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

(>Guido van Rossum (creator of <_tweeted this as a “pro tip”。

但是,PEP8, favors,使用连续的单线评论

# This is a multiline
# comment.

......这也是你在许多项目中发现的。 文本编辑通常可以轻松地这样做。

问题回答

接受的答复......

你们可以使用三条引证。 当他们不做教导时(首先在班级/职级/摩台),他们就会被忽视。

这根本不是事实。 与评论不同的是,三条引用的插图依然平坦,必须具有巧妙的有效性,而不论它们出现在源码中。

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

页: 1

ValueError: invalid x escape

[......]

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

页: 1

作出多线评论的唯一途径是......

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

在A/63/12.7中,多线评论是:

"""
This is a
multilline comment
"""

如果你身处一个班子,你就应该适当打字。

例如:

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

AFAIK,Sharma don t有 block击。 为评论个别线路,您可使用<代码>#。

如果你使用, 栏目对有简短的评论。 http://en.wikipedia.org/wiki/Vim_%28text_editor%29#Interface”rel=“noretinger”>gVim Emacs 具有类似特点。

我认为,只有多线铺设了。 然而,大多数(如果不是全部的话)民主选举学会都有一个简短的钥匙来评论多种法典。

如果你发表评论

"""
long comment here
"""

在手稿中,Adhurc/linters赢得了承认。 由于上述评论不属于标准建议的一部分,因此将重述。 更好使用

# Long comment
# here.

如果您使用Vim ,你可以像commentary.vim,通过紧迫密码/code>自动发表长篇评论。 <代码>Vj选择了两种编码线和gcc 他们发表了意见。

如果你不希望使用像上述那样的假象,你可以使用搜索器,取代。

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

这将取代目前和下行的第一种特性,改为<代码>#。

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

macOS: Select code-block and then +/

视窗:选择性密码锁,然后Ctrl+<

可悲的是,可在上使用作为评论! 因此,遵守按<代码>#排列的每一条线的标准更为安全。

例如:

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

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

我建议不要使用“<条码>”“提出多线评论!

这里是一个简单的例子,可以强调哪些行为可能被视为意外行为:

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

现在看着产出:

I am a string

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

多条线体没有作为评论处理,而是与<代码”相加。 显然,I m还是一个插图:,以形成一个单一的座标。

www.un.org/Depts/DGACM/index_spanish.htm 如果你想根据准则:

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

产出:

I am a string
clearly I am also a string

您也可以尝试这样做(在引用时,对第一个问题的意见应当引用<代码>):

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

无论在<代码>之间,“之间,都将作评论。

如果您正在研究单一线评论,则见#

扎尔多线评论:

对我来说,“”和“”。

例:

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

例:

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

如果你按照守则撰写评论,你必须撰写评论,在标前留下2个空间,在标书上留下1个空间。

print("Hello World")  # printing

如果你就一条新路线发表评论,你必须写一句话,把1个空间用在标记上。

# single line comment

撰写评论的时间超过1行,请使用3字。

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

On Zhu 2.7.13:

单一:

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

请注意,直面字面直面直面的散射特性只是一种散射特性。

dial = "发出紧急呼吁的第100号。"
print(dial)

发出紧急呼吁的第100号。

单线或多线评论也可使用散射特性。

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

Hello

World

用三重两点文字来补充文字。

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!

在案文中加上三倍的单一引文,供作组论。

   
I don t care the parameters and
docstrings here.
   

利用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
   

以及

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

它将对一个单一/多行/代码表示意见,编号<>#。

我认为这是最容易的。

例如,一个部分评论:

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

是的,你只能使用

   
Multiline!
(?)
   

"""
Hello
W或ld!
"""

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

# This is also
# a multiline comment.

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

But you can edit them. F或 example, you can change the sh或tcut from Ctrl / to Ctrl Shift C.

<><>strong>WARNING!

  1. Be careful, don t overwrite other sh或tcuts!
  2. Comments have to be c或rectly 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+ 五) 进入视觉模式。

利用arrow钥匙选择要评论的所有线。

Press Shift+ 页: 1

Press # (or Shift+3)。

Press Esc.

仅用<条码>#就每一条线发表单一线评论:

# 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
   

而且,提到你可以接触像这样的一类物体。

myobj.__doc__

你们可以使用以下方法。 这称为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 + /

我读到了这样做的各种途径的所有缺点。

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

  1. It is obvious to any other programmer this is a comment. It s self-descriptive.
  2. It compiles
  3. It doesn t show up as a doc comment in help()
  4. It can be at the top of the module if desired
  5. It can be automated with a macro.
  6. [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)
  7. 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

  1. It s hard to remember. It s a lot of typing. This con can be eliminated with a macro.
  2. 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".
  3. 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.
  4. It s not the official way, so Pylint might complain about it. I don t know. Maybe; maybe not.

这里是《联邦法典》的宏观尝试,尽管我尚未测试:

{
    "key": "ctrl+shift+/",
    "command": "editor.action.insertSnippet",
    "when": "editorHasSelection"
    "args": {
        "snippet": "block_comment_style =  #[]# 
   #[{TM_SELECTED_TEXT}]#   "
    }
}




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签