python语句解释_在python语言中,如何使用注释

本指南将向你展示如何在python中使用注释。

前提条件一个有效的python编程环境 创建和编辑python文件

python注释基础知识

若要将行标记为注释,请用#和空格:# This is a sample comment.

例如,在下面的Hello World程序中:# Display the text"Hello, World!" on the screen.

print("Hello, World!")

系统只在第二行运行代码,第一行解释了第二行代码应该做什么。

你可以将任意行设置为注释,并可以注释多行,如果代码有不同的块,你可以使用注释来解释每个块:# Define a variable flowers as a list of strings.

flowers = ['rose', 'carnation', 'daisy', 'marigold', 'tulip', 'sunflower']

# Create a for loop to iterate through flowers list, and displays each string item.

for flower in flowers:

print(flower)

块注释

若要将一系列行标记为注释,请在每一行的开头添加一个#:# This is a comment

# that runs on to

# multiple lines.

多行注释

一般来说,应该对每行使用#将它标记为注释,这是推荐和批准的方法,但是,你可能需要一个快速的方法来注释掉整个部分,使用三引号实现与注释类似的功能:def addition_test(a, b):

result = a + b

"""

This is a block

of commented lines.

They aren't parsed and interpreted by the compiler.

"""

return result

注意:正确缩进三引号很重要,如果不这样做,你将看到语法错误。

此方法不会创建真实的注释。相反,它创建一个没有函数的文本常量,只要不添加访问该文本字符串的内容,它就和常规注释相同。

三引号可能很棘手,因为在某些情况下,它会创建一个dosctring。如果你使用以下三元引号:函数签名 类定义 在模块开始时

... Python会将它当成dosctring。

内嵌注释

使用标准#表示内联注释:function

set variable

run command

run additional command # Tricky part: The program breaks if this line is removed.

例如,你可以解释变量的用途,或者留意创建的变量的类型,也可以解释为什么使用特定的命令,如上面的示例所示。

注释掉代码以进行测试

例如,查看这个简单的骰子滚动程序:import random

min = 1

max = 6

roll_again ="yes"

while roll_again =="yes" or roll_again =="y":

print"Rolling the dice..."

print"The values are...."

print random.randint(min, max)

print random.randint(min, max)

# Add two random numbers together for a sum

# while roll_again =="yes" or roll_again =="y":

# print"Rolling the dice..."

# print"You rolled a"

# print random.randint(min,max) + random.randint(min, max)

roll_again = raw_input("Roll the dice again?")

被注释掉的部分未使用。移除#以允许代码测试它。

相关文章

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值