Non-automatic style formatting

Comments

Bad Comments: Example of a comment that doesn’t make sense

# The estimated stock room size minus the rented space 
screen_time = 23 * 1.10


Bad Comments: Example of commenting gone overboard

# Reading in the cereal dataframe
cereal_dataframe = pd.read_csv('data/cereal.csv')

# Saving the cereal dataframe's columns as cereal_columns
cereal_columns = cereal_dataframe.columns 

cereal_dataframe.head() # Displaying the first 5 rows of the cereal_dataframe


Good Comments: Example of a useful comment

# Obtaining the cereals with calories between 130 and 150
cereal_dataframe[(cereal_dataframe['calories'] >130) & (cereal_dataframe['calories'] <150)]

Guidelines according to PEP8 and python.org:

  • Comments should start with a # followed by a single space.
  • They should be complete sentences. The first word should be capitalized unless it is an identifier that begins with a lower case letter.
  • Comments should be clear and easily understandable to other speakers of the language you are writing in.
  • For block comments, each line of a block comment should start with a # followed by a single space and should be indented to the same level as the code it precedes.

BAD comment

# adding 6.99 
cost = cost + 6.99 

Better comment

# Accounting for shipping charges
cost = cost + 6.99 


BAD comment

x = 0

# This code iterates over the numbers 1 to 5 each time adding the number
# to the variable x to get a sum of the numbers from 1, 2, 3, 4, and 5. 
for i in range(1,5):
    x = x + i

Better comment

x = 0

# Sum up the values 1 to 5 
for i in range(1,5):
    x = x + i

Naming convention

Some common variable naming recommendations:

  • Variable names should use underscores
  • Variable names should be lowercase

Fine

lego

Fine

lego_themes

Fine

lego_df

Not Recommended

lego_DF

Not Recommended

LEGO

Not Recommended

legothemes

Variables without Keywords

Don’t Do This

list = []


Or This

def tuple(argument):
    return 


Or This

str = 4
type = 67 * str

Meaningful Names

a = 100 
b = 23
c = 0.56

d = a + b
e = c * d


apples = 100 
bananas = 23
fruit_price = 0.56

fruit_total = apples + bananas
cost = fruit_price * fruit_total

Concise Names

mass_of_the_object_in_motion = 45
the_acceleration_of_the_object_in_motion = 1.8

force_acting_on_an_object = mass_of_the_object_in_motion * the_acceleration_of_the_object_in_motion


mass = 45
acceleration = 1.8

force = mass * acceleration

Let’s apply what we learned!