帮酷LOGO
0 0 评论
文章标签:COMM  comment  python-3  COM  备注  

注释语法

python中的注释以标记(# )和空白字符开始,并继续到行的末尾。

通常,注释将类似于以下内容:


# This is a comment

因为注释不执行,当你运行程序时,你将不会看到注释,

在"Hello ,world"程序中,注释可能如下所示:

hello.py

# Print "Hello, World!" to console
print("Hello, World!")

在遍历列表的for循环中,注释可能如下所示:

sharks.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()函数的说明,在代码的每个缩进级别后,加上注释:

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

内嵌注释

内联注释出现在语句的同一行,在代码本身之后,其他注释一样,它们以标记和单个空白字符开始。

一般情况下,内联注释如下所示:


[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循环,并且可以测试哪一个最好,

guess.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))


注释代码可以让你尝试不同的编程方法,并注释出错误来源。



文章标签:COM  COMM  comment  备注  python-3  

Copyright © 2011 HelpLib All rights reserved.    知识分享协议 京ICP备05059198号-3  |  如果智培  |  酷兔英语