Style Guide

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is

more important. Consistency within one module or function is the most important. However, know when to be

inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best

judgment. Look at other examples and decide what looks best. And don't hesitate to ask.

- Style Guide for Python Code

Naming

  • Only use lowercase characters
  • Separate words with underscores (user_input, not userinput)
  • Variable names should contain full words or common abbreviations (meters_per_mile, not m_per_mi)
  • Don't use a reserved Python word (anything that is colored in your text editor)
  • Variable names should include a word that eludes to its type:
    • integer: e.g. count, number, index, etc.
    • float: e.g. quantity, amount, size, weight, mass, etc.
    • string: name, title, word, sentence, description, etc.
    • boolean: is_ascending, is_sorted, is_full, etc.

Comments

As a reminder, comments in Python are written starting with a #.

At the top of your file, write a comment header with whether you went to TA hours, any collaborators' names, and how long you spent on the assignment.

Try to write comments as their own line of text, coming before the code they discuss. Occasionally, a short comment at the end of a line that makes a comment pertaining only to that line can be used.

Whitespace

Spaces, line breaks, and more!

  • Put spaces around operators ("z = x + y" not "z=x+y")
  • Indent using 4 spaces per indent. This is the default indent when you hit tab in Sublime text, but be careful if you use other text editors that all of your indentations are the same size.
  • Lines should be shorter 80 characters. To break up lines that threaten to go longer, you can use a hanging indent, aligning the extra text with its predecessors on the previous line, which doesn’t have to be exactly 4 spaces. Lines can also be continued using backslashes (\).

This document will be updated as the course progresses.

Want to obsess over style? Read more at https://www.python.org/dev/peps/pep-0008/