• 6 hours
  • Easy

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 5/24/22

Write Clean Code

Log in or subscribe for free to enjoy all this course has to offer!
Man using laptop in an armchair.

Why Is Clean Code Important?

Before we dive into clean coding methods, let’s explore why it is important to keep code as clean as possible.

Think of the messiest and least organized place in your home. It may be a drawer, closet, or even a whole room. How hard is it to find something? If you’ve recently used it, it may not be so bad, but if it’s been a while, things can get tricky.

It’s the same, or worse, with code. If you haven’t looked at it in a few months and didn’t write it cleanly, it can take forever to remember which function does what and how things fit together.

Now imagine that you inherited someone else’s disorganized drawer, closet, or room, and they no longer live there. That’s what it’s like to work on someone else’s code when they haven’t kept it clean!

You need to have a shared definition with other developers of what it means to write clean code. This way, you can better understand it without needing to know the person who wrote it.

Now that you understand why you need to code cleanly let’s look at how to write it.

Don’t Repeat Yourself

The holy grail of coding standards is DRY, or don’t repeat yourself. As a programmer, you want to make things as fast and efficient as possible and automate as much as you can. If you find yourself copying and pasting code a lot (or anything really), it’s usually a sign that you can automate the process.  

Let’s say you want to calculate a conversion rate and print it out for multiple campaigns. You could copy and paste for each campaign like the code below:

conversion_rate1 = first_campaign['visitors'] / first_campaign['conversions']
conversion_rate2 = second_campaign['visitors'] / second_campaign['conversions']
conversion_rate3 = third_campaign['visitors'] / third_campaign['conversions']

If you start writing code (or seeing) like this, the first thing you want to do is think about turning it into a function. You can write a function called  calculate_conversion_rate  and do all of this in one go.

def calculate_conversion_rate(campaign):
conversion_rate = campaign['visitors'] / campaign['conversions']
return conversion_rate
calculate_conversion_rate(first_campaign)
calculate_conversion_rate(second_campaign)
calculate_conversion_rate(third_campaign)

The two code snippets above accomplish the same thing - only one is much cleaner and follows the DRY principle!

The Single-Responsibility Principle

When you’re organizing anything, it’s best to have a single set place for every item because you know that will make it easier to find. It’s the same when writing functions. You want to have each one be responsible for a single function - and nothing more.

Let's say you want to calculate the conversion rates for a few campaigns and then save the data into a CSV. Instead of having one function called   calculate_conversion_rate_save_to_csv() let's separate the two tasks into separate functions:

  • calculate_conversion_rate()  

  • save_to_csv()  

Each function should be responsible for a single task. Once you start trying to accomplish more than one thing with a single function, it’s harder to understand what you wanted to do in the first place.

Separating responsibilities helps you set a more descriptive name for the function, debug more easily, and better understand the code.

Comment Your Code

Comments are a great way to remind yourself and other developers what the code should be doing.

There are different standards for commenting - you want your code to be readable enough that you don’t need too many for someone to understand it.

In Python, there are single-line and multi-line comments.

Single line comments are denoted with  #  before and after. Below is an example of a single-line comment about a method.

#this is a comment

Multi-line comments have  three quotation marks  """  before and after: 

"""
This is a
multi-line comment
"""

Respect Coding Standards

In general, you read code much more often than you write it. That’s why it’s important to have guidelines to improve readability and make it as consistent as possible.

The official style guide for Python code is a document called PEP 8. It contains rules and best practices that help standardize how developers write Python.

More generally, the philosophies behind writing Python correctly are captured by a document called PEP 20

Explicit is better than implicit.
Simple is better than complex.
(...)
READABILITY COUNTS.

It's vital to be familiar with this "Zen of Python," as it's called. I also recommend referring to PEP when new questions come up in your Python coding projects.

Level-Up: Debug Python Code

Let's finish off this chapter on writing clean code with a debugging challenge! Code bugs or errors are issues with your code that prevent your program from working as it should, or from working at all. Getting some practice with debugging will give you the opportunity to apply everything you've learned so far about writing functional Python code!

This five-step exercise will walk you through identifying and correcting four common types of bugs: string errors, indentation errors, syntax errors, and logic errors.

Let's do this! 😎

Coding application
Houston... ?
It seems you're not connected to the internet.
You are not signed in

Sign in to access coding exercises and test your new skills.

Make sure to practice in this chapter before moving on.
 

Let’s Recap!

  • Writing clean, standard code helps you and other developers to have a consistent, shared understanding of what the code is doing.

  • DRY: don’t repeat yourself in code! Copy and pasting is a huge no-no.

  • Single-responsibility: let each function have only one purpose for better readability.

Part 2 Summary

Congratulations! You've reached the end of Part 2 of this course and can now program logic into your Python code. You've accomplished a lot!

  • You've used conditionals and loops to control your logic flow.

  • You've written functions to separate code out for specific purposes. 

  • You've learned the importance of clean code.

Once you’ve completed the quiz, you’ll be eligible for the course certificate. Congrats! 

Part 3 Preview

You may have the basics down, but you aren't done leveling-up! An optional challenge awaits you in the final part of the course, designed to provide you with an opportunity to apply your new skills further, as well as add some additional skills to your tool belt.

You’ve come this far. Remember the tips from the orientation chapter: we learn by doing and we learn by challenging ourselves. Now it is time to truly flex your Python coding skills and take them to the next level. 😁

Example of certificate of achievement
Example of certificate of achievement