This lesson reviews best practices associated with clean coding.
At the end of this activity, you will be able to:
- write code using the PEP 8 style guide
What You Need
Python 3.x and
Jupyter notebooks to complete this tutorial. Also you should have an
earth-analytics directory setup on your computer with a
/data directory with it.
Clean code means that your code is organized in a way that is easy for you and for someone else to follow / read. Certain conventions are suggested to make code easier to read. For example, many guides suggest the use of a space after a comment. Like so:
#poorly formatted comments are missing the space after the pound sign. # good comments have a space after the pound sign
While these types of guidelines may seem unimportant when you first begin to code, after a while you’re realize that consistently formatted code is much easier for your eye to scan and quickly understand.
Consistent, Clean Code
Take some time to review PEP 8 Python Style Guide. From here on in, we will follow this guide for all of the assignments in this class.
Object Naming Best Practices
Keep object names short: this makes them easier to read when scanning through code.
Use meaningful names: For example:
precipis a more useful name that tells us something about the object compared to
Don’t start names with numbers! Objects that start with a number are NOT VALID in
Avoid names that are existing functions in Python: e.g.,
for, see here for more reserved names.
A few other notes about object names in
Pythonis case sensitive (e.g.,
weight_kgis different from
- Avoid other function names (e.g.
- Use nouns for variable names, and verbs for function names.
- Avoid using dots in object names - e.g.
my.dataset- dots have a special meaning in R (for methods) and other programming languages. Instead use underscores
Take a look at the code below.
- Create a list of all of the things that could be improved to make the code easier to read / work with.
- Add to that list things that don’t fit the PEP 8 style guide standards.
- Try to run the code in
Python. Any issues?
variable = 3 * 6 meanvariable = variable # calculate something important mean_variable = meanvariable * 5 thefinalthingthatineedtocalculate = mean_variable + 5
# get things that are important import pandas as pd %matplotlib inline
import earthpy as et paths = et.data.get_data('week_02') my_data = pd.read_csv(paths) my_data.head()
my_data.plot('DATE', 'PRECIP', figsize = (20, 20), color = 'purple');