By Zed A. Shaw

LPTHW Ex 38 Done: Reading Code

Another exercise I just wrote for Learn Python The Hard Way where they do some code reading. In Exercise 37 they reviewed all of the Python symbols in order to get their vocabulary straight. In this one they apply that exercise to try understanding code.

You should now go out and find some Python code to read. You should be finding and reading any Python code you can and trying to steal ideas that you find. You actually should have enough knowledge to be able to read, but maybe not understand what the code does. What I'm going to teach you in this lesson is how to apply things you've learned to understand other people's code.

First, take the code you want to understand and print it out. 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, you should 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're 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 don't need the printouts anymore.

Extra Credit

  1. Go find out what a "flow chart" is and write a few.
  2. If you find errors in code you're reading, try to fix them and send the author your changes.