Style Guide

CSE 160 Python Style Guide

This list is meant to be a reference for the specific style standards the staff of CSE 160 will expect in homework submissions. This is to ensure consistency and fairness in grading.

Remember there are "official" Python Style guidelines you can refer to here for more detail. (Here are also Google's Python guidelines).

Naming Conventions

Note: Other programming languages (e.g. Java) have different conventions for naming. Use the conventions of the language you are working in.

Variable Names

Variable names in Python should be descriptive, concise, and lowercase, with words separated by underscores. Students shouldn't use single letter names for variables that should really be 'factorial', 'current_sum', or 'reciprocal' but they are fine for loop variables.

  • You should use descriptive variable names, such as "factorial" or "current_sum", that describe the value the variable contains.
  • In Python, it’s recommended to name variables and functions in a certain way so that other Python programmers can read your code more easily. Here are some examples of variable names: "num_lines", "triangular_number", "running_sum", "my_friends", etc.
  • Avoid using python keywords for variable names, such as 'class', 'print', 'import', or 'return'. A list of keywords can be found by typing the following into the Python interpreter
import keyword
keyword.kwlist

Good:

total
height_sum
average_weight
age

Bad:

t
NumberSum  # bad when used as a variable name
a_w
whats_my_age_again  # too verbose, detracts from readability
return  # python keyword

Function Names

Function names in Python should be concise, descriptive, and lower-case with words separated by underscores.

Examples:

read_image(filename)
compute_avg(x, y, z)
max_neighbors(grid, i, j)

Whitespace

Blank Lines

There should be two blank lines separating function definitions from other portions of code. Try to minimize blank lines within function definitions, except when separating complex chunks of code/logic to provide readability. Example 2 is

Good Example 1: (2 blank lines separating function bodies)

# other code

    
def read_image(filename):
    # implementation code

    
# other code

Good Example 2: (blank line separating "complex" chunks of code)

def compute_avg(x, y, z):
    """
    Sums the given numbers and returns the average.
    """
    sum_val = x + y + z

    # compute and return the average value
    result = sum_val / 3.0
    return result

    
# more code below

Bad Example 1: (not enough blank lines)

# other code
def get_height():
    # implementation code
# other code

Bad Example 2: (too many blank lines)

# other code

def get_height():

    # implementation code



    # other implementation code for get_height()

# other code

Space Between Operators

Include spaces between mathematical and logical operators and other elements in an expression. Mathematical operators include +, -, /, *, and **. Logical operators include ==, <=, >=, <, and >. Limit space delimiters to 1 space, to avoid unnecessary whitespace. The exception to this is parentheses, which can be directly adjacent to whatever they are enclosing.

Good:

x + y
(sum ** 2) + 4 * val - 1
x * (4 + 6)
b + math.sqrt(4 * max_val)

Bad:

x+y			# not enough spaces
(sum**2)+4*val-1 	# not enough spaces
x * ( 4 + 6 )   	# unnecessary spaces around parentheses
b +   math.sqrt( 4 *     max_val)  # inconsistent spacing

Note: While in some cases spacing around operators can be left to personal preference, for CSE 160 we will hold your code to this standard as it adds readability to your code.

Space Between Function Names and Parameter List

Avoid adding extra space(s) between a function name and its associated parameter list. For example, you should write, "range(x)" instead of "range (x)" (in other words, do not put a space between ‘range’ and the opening parenthesis). Using the space suggests--incorrectly--that the parenthesis are for grouping an expression, when in fact they are for calling the function.

You should, however, include spaces between individual parameters in the parameter list. This makes your function definitions and calls more readable.

Good:

x = math.sqrt(n)
range_vals = range(n, 4)

Bad:

x = math.sqrt (n)  # too much space before the parenthesis
range_vals = range(n,4)  # no spaces between parameters

Line Length

Limit lines of code/comments to 80 characters to provide readability. If a line extends past this limit, split it onto another line.

Commenting

Include a header comment at the top of a file to describe what the function of a python program is. Also, long blocks of code with a particular purpose or small bits of particularly complex code should be labeled/explained by a comment (using #) on the preceding line(s).

Each function should contain a docstring (Using """ or ''') describing what the function does and any parameters the function takes and values it returns (if any).

Avoid commenting on information that is unnecessary or obvious to other programmers reading your code (i.e. "initialize variable" or "nested for loop" or "increment count").

Use proper spacing with your comments as well:

#Don't do this
# Do this
x += 5# This is too close to the code!
x += 5 # Also too close.
x += 5  # Do this (use at least two spaces)
x += 5                                              # Too much!

Avoid unnecessary nested if statements or a series of if statements

Avoid nesting if statements that can be written as one if statement.

Do this:

if val > 120:
    print("Green!")
elif val > 80:
    print("Blue!")
elif val > 32:
    print("Red!")
else:
    print("Orange!")

Instead of this:

if val > 120:
    print("Green!")
else:
    if val > 80:
        print("Blue!")
    else:
        if val > 32:
            print("Red!")
        else:
            print("Orange!")

If the intent is for only one block of code to execute, be sure to use if, elif, else instead of a series of ifs.

Do this:

if color == 'Red':
    # code here
elif color == 'Green':
    # code here
elif color == 'Blue':
    # code here
elif color == 'Yellow':
    # code here

Instead of this:

if color == 'Red':
    # code here
if color == 'Green':
    # code here
if color == 'Blue':
    # code here
if color == 'Yellow':
    # code here

Avoid looping over the same data multiple times in a row

Avoid repeated for loops if you can perform all the operations inside one loop.

Do this:

for color in color_list:
    if color == 'Red':
        # code here
    elif color == 'Green':
        # code here
    elif color == 'Blue':
        # code here
    elif color == 'Yellow':
        # code here

Instead of this:

for color in color_list:
    if color == 'Red':
        # code here

for color in color_list:
    if color == 'Green':
        # code here

for color in color_list:
    if color == 'Blue':
        # code here

for color in color_list:
    if color == 'Yellow':
        # code here

Boolean "zen"

  • Expressions that evaluate to booleans are great because you don't have to do any the testing with == and != like you do with other types. Treat them like the True and False that they are. Remember that you can use not to negate a boolean value, as in example 2 below.

If you have a boolean value is_sunny:

Example 1

Good:

if is_sunny:
    be_happy()

Bad:

if is_sunny == True:
    be_happy()

Example 2

Good:

return not is_sunny

Bad:

return is_sunny == False

Example 3

Good:

return is_sunny

Bad:

if is_sunny:
    return True
else:
    return False

Replicating code

If you find yourself cutting and pasting lines of code stop and think if this code could be put into a loop or a function instead.

Replicating code from functions that you already wrote

Don't write the same code again if you already have a function that performs that action. Just call the function.

Perhaps two similar but not identical pieces of code can be turned into a function by using parameters.

Miscellaneous

Advanced Material

For homework assignments in CSE 160, avoid using programming concepts not yet presented in lecture.

Lingering Debug Code

Please remove any print statements or unnecessary computations that you added to help debug errors before you turn in your program. Don't just leave unnecessary code commented out. It makes the real code harder to read.

Avoid Global Variables

You should avoid using global variables inside of functions. If you use a variable in a function, you should always pass it as a parameter. Although Python lets you use global variables inside functions, it's very dangerous to do so because it makes it harder to predict what the function will return. Using parameters instead of global variables also helps people calling your function understand what your function does, because they can see what it operates on (what they pass in as arguments).

Unnecessary Use of Parentheses

Avoid using excessive parentheses in your code, when not needed. Too many parentheses detract from readability.

Good:

(x + 4) / (6 ** (y ** 2))   # readable

Bad:

((((x) + (4))) / ((6) ** ((y) ** 2)))   # less readable