Prelab 1 Notes

Good coding practice

A little about style

We should always aim for well-chosen, that is self-documenting, names for functions, variables, etc., and informative (but pithy) comments. The quality of your coding style will also be a factor in your programming assignment grades. Code should be written to be read not just executed! And the most likely person to read your code is “future you”, so think of good style as being kind to future you.

There is no one definition of “good style”, but in general it is combination of efficiency, readability and maintainability (that is, can your code be readily updated/enhanced by you or others).

We will discuss style more as we go, but it is never too early to develop good habits. In general we will follow the PEP 8 style guide.

Being DRY

You will often hear the acronym ‘DRY’ for Don’t Repeat Yourself, often as used as a verb. For example, “DRY it up”. The goal is to eliminate duplicated code. Why? Duplicated code makes it harder to read and to update your code (to correct a mistake you might have to change a computation in many places!). Often the way to DRY it up is encapsulate duplicated code as a function.

Comments

In your first lab we will ask you to comment your code. The purpose of the comments is to describe what your code is doing, not to describe the code itself; you can assume the reader knows Python. But the reader doesn’t necessarily know what you are trying to do.

We will generally encounter two kinds of comments:

  1. Block and inline comments
  2. Docstrings

The former are comments starting with a #, included in the code itself. Everything after the # on the line will not be executed by Python. The second kind of comment, docstrings, are indicated by pairs of triple single or double quotes, can be used as “multi-line” comments, e.g.

"""
A multi-line comment
"""

This provides a structured mechanism for documenting functions, classes, and other entities in your Python code. For example, if you have defined a docstring for a function called welcome, then typing help(welcome) at the shell will print out the docstring for that function.