如何做多行注释?大多数语言都有块注释符号,比如:

/*

*/

当前回答

不幸的是,字符串化不能总是用于注释!因此,坚持在每行前加上#的标准更安全。

这里有一个例子:

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

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

其他回答

使用PyCharm IDE。

可以使用Ctrl+/对代码行进行注释和取消注释。 Ctrl+/用单行注释注释或取消注释当前行或几个选定的行(Django模板中的{#或Python脚本中的#)。 在Django模板中,对选中的源代码块按Ctrl+Shift+/,该代码块会被{% comment %}和{% endcomment %}标记包围。

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

print("Loop ended.")

选择所有行,然后按Ctrl + /


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

# print("Loop ended.")

不幸的是,字符串化不能总是用于注释!因此,坚持在每行前加上#的标准更安全。

这里有一个例子:

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

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

你可以使用下面的方法。这叫做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__

是的,你可以简单地使用

'''
Multiline!
(?)
'''

or

"""
Hello
World!
"""

好处:它有点难,但在旧版本、打印函数或gui中使用更安全:

# This is also
# a multiline comment.

对于这个,你可以选择你想要注释的文本,并按Ctrl /(或⌘/),在PyCharm和VS Code中。

但是你可以编辑它们。例如,可以更改快捷键“Ctrl /” 按Ctrl Shift C。

警告!

小心,不要覆盖其他快捷方式! 注释必须正确缩进!

希望这个回答能有所帮助。祝你下次写出其他答案时好运!

在其他答案中,我发现最简单的方法是使用IDE注释函数,该函数使用Python注释支持#。

我正在使用Anaconda Spyder,它有:

Ctrl + 1 -注释/取消注释 Ctrl + 4 -注释代码块 Ctrl + 5 -取消注释代码块

它可以用#注释/取消注释一行/多行代码。

我觉得这是最简单的。

例如,一个块注释:

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