习题 2: 注释和井号
程序里的注释是很重要的。它们可以用自然语言告诉你某段代码的功能是什么。在你想要临时移除一段代码时,你还可以用注解的方式将这段代码临时禁用。接下来的练习将让你学会注释:
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print "I could have code like this." # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."
从现在开始,我将要酱婶儿地写代码。有一点非常重要,那就是你得明白所有的一切都不比遵循字面的意思。你的屏幕所显示的和你的程序也许看起来和我的并不相同,但是最重要的是你写进编辑器的、键入那个文件的文本。实际上,我可以使用任何的文本编辑器,而且结果都会是一样的。
What You Should See
$ python ex2.py
I could have code like this.
This will run.
再说一次,我不打算给你看那些Terminal的截屏了。你应该明白的是上面的内容在你的输出中并不一定要看起来一一对应,但是你的注意力应该集中在在第一个$ python
...和最后一个$之间。
Study Drills
- 弄清楚"#"符号的作用。而且记住它的名字。(中文为井号,英文为 octothorpe 或者 pound character)。
- 打开你的
ex2.py文件,从后往前逐行检查。从最后一行开始,倒着逐个单词单词检查回去。 - 有没有发现什么错误呢?有的话就改正过来.
- 朗读你写的习题,把每个字符都读出来。有没有发现更多的错误呢?有的话也一样改正过来。
Common Student Questions
Are you sure # is called the pound character? |
|---|
| I call it the octothorpe because that is the only name that no country uses and that works in every country. Every country thinks its name for this one character is both the most important way to do it and the only way it's done. To me this is simply arrogance and, really, y'all should just chill out and focus on more important things like learning to code. |
If # is for comments, then how come # -*- coding: utf-8 -*- works? |
| Python still ignores that as code, but it's used as a kind of "hack" or workaround for problems with setting and detecting the format of a file. You also find a similar kind of comment for editor settings. |
Why does the # in print "Hi # there." not get ignored? |
The # in that code is inside a string, so it will be put into the string until the ending " character is hit. These pound characters are just considered characters and aren't considered comments. |
| How do I comment out multiple lines? |
Put a # in front of each one. |
*I can't figure out how to type a # character on my country's keyboard? |
| Some countries use the Alt key and combinations of other keys to print characters foreign to their language. You'll have to look online in a search engine to see how to type it. |
| Why do I have to read code backward? |
| It's a trick to make your brain not attach meaning to each part of the code, and doing that makes you process each piece exactly. This catches errors and is a handy error-checking technique. |
Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong