变量和简单数据类型
五、注释
注释可以让我们使用自然语言在程序中添加说明。
5.1如何编写注释
在Python中使用(#)标识。井号后面的内容都会被Python解释器忽略。
如下所示:
print("hellow word")
#向大家问好
运行结果如下:
hellow word
在这里Python解释器将忽略第一行,只执行第二行。
5.2注释的编写及作用
- 阐述代码工作原理。
- 编写有意义的注释。
- 编写清晰、简洁的注释。
- 方便自己以及其他人阅读代码。
六、Python之禅
在终端会话中执行命令:
import this
运行结果如下:
The Zen of Python, by Tim Peters
Beautiful is better than ugly. #漂亮而优雅
Explicit is better than implicit. #清晰而明了
Simple is better than complex. #简单总比复杂好
Complex is better than complicated. #复合总比复杂好
Flat is better than nested. #平面总比嵌套好
Sparse is better than dense. #稀疏总比稠密好
Readability counts. #可读性很重要。
Special cases aren't special enough to break the rules. #特殊情况不足以打破规则。
Although practicality beats purity. #虽然实用性胜过纯粹
Errors should never pass silently. #错误永远不应该通过沉默
Unless explicitly silenced. #除非显式沉默
In the face of ambiguity, refuse the temptation to guess. #面对模棱两可,拒绝猜测的诱惑。
There should be one-- and preferably only one --obvious way to do it. #最好只有一个明显的方式来做它。
Although that way may not be obvious at first unless you're Dutch. #虽然这种方式可能是不显而易见的,不过,除非你是荷兰人。
Now is better than never. #现在总比没有好
Although never is often better than *right* now. #虽然从来没有比现在更好
If the implementation is hard to explain, it's a bad idea. #如果实现很难解释,那么这不是一个好主意。
If the implementation is easy to explain, it may be a good idea. #如果实现很容易解释,那么这可能是个好主意。
Namespaces are one honking great idea -- let's do more of those! 名称空间是一个伟大的想法-让我们做更多这样的事情!
这便是由Tim Peters 撰写的Python之禅。
本章小结
在本章中我们学习了:
- 如何使用变量
- 如何创建描述性变量名以及如何消除名称错误和语法错误
- 字符串是什么,以及如何使用大小写显示字符串
- 使用空白来显示整洁的输出,以及如何剔除字符串中多余的空白
- 如何使用整数和浮点数
- 使用数值数据时需要注意的意外行为
- 编写说明性注释
在下一章我们将学习如何在被称为列表的变量中存储信息,以及如何通过遍历列表来操作其中的信息。