如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
当前回答
Python确实有一个多行字符串/注释语法,在这种意义上,除非用作文档字符串,多行字符串不会生成字节码——就像#- prependedcomments一样。实际上,它的作用完全像注释。
另一方面,如果您说这种行为必须在官方文档中记录,才能成为真正的注释语法,那么是的,您说它不保证是语言规范的一部分是正确的。
在任何情况下,您的文本编辑器还应该能够轻松地注释掉所选区域(通过在每行前面单独放置#)。如果不是,切换到一个文本编辑器。
在没有特定文本编辑功能的情况下使用Python编程可能是一种痛苦的体验。找到正确的编辑器(并知道如何使用它)会对如何感知Python编程体验产生很大的影响。
文本编辑器不仅应该能够注释掉所选区域,还应该能够轻松地将代码块向左或向右移动,并且当您按下Enter时,它应该自动将光标置于当前缩进级别。代码折叠也很有用。
为了防止链接衰减,以下是Guido van Rossum的推文内容:
Python提示:你可以使用多行字符串作为多行注释。除非用作文档字符串,否则它们不会生成代码!: -)
其他回答
Python中的内嵌注释以哈希字符开始。
hello = "Hello!" # This is an inline comment
print(hello)
你好!
注意,字符串文字中的哈希字符只是一个哈希字符。
dial = "Dial #100 to make an emergency call."
print(dial)
拨打100拨打紧急电话。
散列字符也可以用于单行或多行注释。
hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)
你好 世界
用三双引号将文本括起来以支持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"))
你好约翰!
在文本中加上三个单引号作为块注释。
'''
I don't care the parameters and
docstrings here.
'''
从公认的答案…
你可以使用三引号字符串。当它们不是文档字符串(类/函数/模块中的第一件事)时,它们将被忽略。
这是不正确的。与注释不同,三引号字符串仍然被解析,并且必须在语法上有效,无论它们出现在源代码中的哪个位置。
如果你试图运行这段代码…
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
你会得到…
ValueError: invalid \x escape
...Python 2。x或…
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape
...Python 3.x。
做被解析器忽略的多行注释的唯一方法是…
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()
AFAIK, Python没有块注释。对于注释单个行,可以使用#字符。
如果你正在使用notepad++,有一个块注释的快捷方式。我相信其他的像gVim和Emacs也有类似的特性。
不幸的是,字符串化不能总是用于注释!因此,坚持在每行前加上#的标准更安全。
这里有一个例子:
test1 = [1, 2, 3, 4,] # test1 contains 4 integers
test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'
好吧,你可以试试这个(当运行引号时,第一个问题的输入应该用'引号括起来):
"""
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)
"""之间的任何内容都将被注释。
如果你正在寻找单行注释,那么它是#。