Python注释代码
介绍
注释是计算机程序中存在的被编译器和解释器忽略的行。在程序中使用注释可以使代码对人类更具可读性,因为它提供了有关程序每个部分正在做什么的一些信息或解释。
根据您程序的目的,注释可以作为给自己的注释或提醒,也可以写成其他程序员能够理解您的代码在做什么的意图。
一般来说,在编写或更新程序时写注释是个好主意,因为以后很容易忘记你的思维过程,而且以后写的注释从长远来看可能不太有用。
注释语法
Python 中的注释以井号 ( #
) 和空白字符开头,并一直到行尾。
通常,评论看起来像这样:
# This is a comment
复制
因为注释不会执行,所以当您运行程序时,您不会在那里看到任何注释指示。注释在源代码中供人类阅读,而不是供计算机执行。
在“你好,世界!”中 程序,注释可能如下所示:
你好.py
# Print “Hello, World!” to console
print("Hello, World!")
复制
鲨鱼.py
# Define sharks variable as a list of strings
sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']
# For loop that iterates over sharks list and prints each string item
for shark in sharks:
print(shark)
复制
注释应该与它所注释的代码在相同的缩进级别上进行。也就是说,没有缩进的函数定义将有一个没有缩进的注释,并且每个缩进级别后面的注释都与它正在注释的代码对齐。
例如,以下是如何在 Python 3 教程中制作简单计算器程序中的 again()
函数的注释方式,注释在代码的每个缩进级别之后:[](https://www.digitalocean.com/community/tutorials/how-to-make-a-simple-calculator-program-in-python-3)
计算器.py
...
# Define again() function to ask user if they want to use the calculator again
def again():
# Take input from user
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
# If user types Y, run the calculate() function
if calc_again == 'Y':
calculate()
# If user types N, say good-bye to the user and end the program
elif calc_again == 'N':
print('See you later.')
# If user types another key, run the function again
else:
again()
复制
评论是为了帮助程序员,无论是原始程序员还是其他使用或协作项目的人。如果注释不能与代码库一起正确维护和更新,最好不要包含注释,而不是编写与代码相矛盾或将相矛盾的注释。
在评论代码时,您应该寻找答案背后的原因 ,而不是什么 或如何 。除非代码特别棘手,否则查看代码通常可以知道代码在做什么或它是如何做的。
阻止评论
块注释可用于解释更复杂的代码或您不希望读者熟悉的代码。这些较长格式的注释适用于后面的部分或全部代码,并且也与代码在同一级别缩进。
在块注释中,每一行都以井号和一个空格开头。如果您需要使用多个段落,它们应由包含单个井号的行分隔。
下面是一个块注释的例子,它定义了 main()
下面定义的函数中发生的事情:
# The main function will parse arguments via the parser variable. These
# arguments will be defined by the user on the console. This will pass
# the word argument the user wants to parse along with the filename the
# user wants to use, and also provide help text if the user does not
# correctly pass the arguments.
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"word",
help="the word to be searched for in the text file."
)
parser.add_argument(
"filename",
help="the path to the text file to be searched through"
)
...
复制
块注释通常用于操作不那么直接并因此需要彻底解释的情况。您应该尽量避免对代码进行过度注释,并且应该倾向于相信其他程序员能够理解 Python,除非您是为特定受众编写的。
内嵌注释
内联注释出现在语句的同一行,紧跟代码本身。与其他注释一样,它们以井号和单个空格字符开头。
通常,内联注释如下所示:
[code] # Inline comment about the code
复制
内联注释应该谨慎使用,但可以有效地解释代码中棘手或不明显的部分。如果您认为自己将来可能不记得正在编写的代码行,或者如果您正在与认识的人合作,但他们可能并不熟悉代码的所有方面,它们也很有用。
例如,如果您在 Python 程序中没有使用大量数学,您或您的合作者可能不知道以下内容会创建一个复数,因此您可能希望包含一个关于它的内联注释:
z = 2.5 + 3j # Create a complex number
复制
内联注释也可以用来解释做某事背后的原因,或一些额外的信息,如:
x = 8 # Initialize x with an arbitrary number
复制
只有在必要时才应使用行内的注释,并且它们可以为阅读程序的人提供有用的指导。
注释掉测试代码
除了使用注释作为记录代码的一种方式之外,哈希标记还可用于注释掉您在测试或调试当前创建的程序时不想执行的代码。也就是说,当您在实现新的代码行后遇到错误时,您可能需要将其中的一些注释掉,以查看是否可以解决准确的问题。
使用哈希标记还可以让您在确定如何设置代码时尝试替代方案。例如,您可能要决定在Python 游戏中使用while
循环还是 for
循环,并且可以在测试和确定哪个可能最好时注释掉其中一个:
猜测.py
import random
number = random.randint(1, 25)
# number_of_guesses = 0
for i in range(5):
# while number_of_guesses < 5:
print('Guess a number between 1 and 25:')
guess = input()
guess = int(guess)
# number_of_guesses = number_of_guesses + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
print('You guessed the number!')
else:
print('You did not guess the number. The number was ' + str(number))
复制
用井号注释代码可以让您尝试不同的编程方法,并通过系统地注释和运行程序的某些部分来帮助您找到错误的根源。
结论
在 Python 程序中使用注释有助于使您的程序对人类(包括未来的自己)更具可读性。包含相关且有用的适当注释可以使其他人更容易与您在编程项目上进行协作,并使您的代码的价值更加明显。