Readability
A well written program should not only be efficient and correct, but it should also be easy to read. While Python is very flexible in terms of program and code structure, good use syntax, stylistics elements, and white space can help make your code more readable and easier to comprehend. Remember, just because the syntax of the language allows you to do something, doesn't mean it's the best choice to employ when attempting to create a well structured program. SpacingHorizontal Spacing. Horizontal spacing within statements can help to make your code easier to read, especially when printed in a small font size.
x = y * z + 50 - x isValid = x >= 0 and x < 100
Vertical Spacing. Blank lines should be used to separate long, logically related blocks of code. To be effective, blank lines should be used consistently. Specifically:
Long LinesWhile it may be easy to read your source file within the text editor or IDE, remember that in many cases, your source code will be viewed from printed copy of the text file. In this case, the long lines have to be wrapped in order for them to fit on the page. This can produce ugly and distracting results.
Wrapping LinesWhen a statement is wrapped, the part continued on the next line should be indented and aligned, if possible, with the previous statement. For example, consider the long expression in the example below and notice how the continued part is indented and aligned with the first part of the expression. result = (self._value1 * self._value2 + anotherValue) \ * self._numberOfValues If a string (other than the triple quotes version) is too long to fit on one line, it should be manually wrapped using the backslash between separate strings. Do not use the backslash within a string literal. The example below shows how to correctly wrap long literal strings. myString = "this is a long"\ " string wrapped across 2 lines." If a logical expression must be split across more than one line, it should be wrapped such that the expression is easy to follow. It should never be split between a relational operator, but it can be split between a boolean operator. For example, if amount <= amountRequired and \ amountOwed > 0.0 : If an assertion or exception statement must be wrapped, the string containing the message should fit on a single line and not split across multiple lines. For example, assert value > 0 and node is not None, \ "The value must be > 0 and the list can not be empty."
|