《笨办法学 Python》—— 阅读代码

首先把你想要理解的代码打印到纸上。没错,你需要打印出来,因为和屏幕输出相比,你的眼睛和大脑更习惯于接受纸质打印的内容。一次最多打印几页就可以了。

然后通读你打印出来的代码并做好标记,标记的内容包括以下几个方面:

1.函数以及函数的功能。
2.每个变量的初始赋值。
3.每个在程序的各个部分中多次出现的变量。它们以后可能会给你带来麻烦。
4.任何不包含 else 的 if 语句。它们是正确的吗?
5.任何可能没有结束点的 while 循环。
6.最后一条,代码中任何你看不懂的部分都记下来。

接下来你需要通过注解的方式向自己解释代码的含义。解释各个函数的使用方法,各个变量的用途,以及任何其它方面的内容,只要能帮助你理解代码即可。

最后,在代码中比较难的各个部分,逐行或者逐个函数跟踪变量值。你可以再打印一份出来,在空白处写出你要“追踪”的每个变量的值。

一旦你基本理解了代码的功能,回到电脑面前,在屏幕上重读一次,看看能不能找到新的问题点。然后继续找新的代码,用上述的方法去阅读理解,直到你不再需要纸质打印为止。


First, print out the code you want to understand. Yes, print it out, because your eyes and brain are more used to reading paper than computer screens. Make sure you only print a few pages at a time.

Second, go through your printout and take notes of the following:

  1. Functions and what they do.
  2. Where each variable is first given a value.
  3. Any variables with the same names in different parts of the program. These may be trouble later.
  4. Any if-statements without else clauses. Are they right?
  5. Any while-loops that might not end.
  6. Finally, any parts of code that you can't understand for whatever reason.

Third, once you have all of this marked up, try to explain it to yourself by writing comments as you go. Explain the functions, how they are used, what variables are involved, anything you can to figure this code out.

Lastly, on all of the difficult parts, trace the values of each variable line by line, function by function. In fact, do another printout and write in the margin the value of each variable that you need to "trace".

Once you have a good idea of what the code does, go back to the computer and read it again to see if you find new things. Keep finding more code and doing this until you do not need the printouts anymore.



阅读更多
个人分类: Python
上一篇《笨办法学 Python》 学习笔记02
下一篇《笨办法学 Python》 学习笔记03 —— Function、List、Dist
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭