Writing Clean and Readable Python Code: Examples and Tips

Sebastien Simon
5 min readDec 28, 2022

--

As a Python developer, writing clean code is an important skill to master. Not only does it make your code easier to read and maintain, but it can also help you avoid bugs and improve the overall performance of your software. Here are some tips for writing clean code in Python:

Use descriptive and meaningful variable names: Choosing clear and descriptive names for your variables is one of the most important things you can do to improve the readability of your code. Instead of using abbreviations or single letters, try to choose names that accurately describe the purpose of the variable. For example, instead of using n for a variable that represents a count, you might use count or num_items. This will make it easier for others (or future you) to understand what the code is doing without having to constantly refer back to the code to decipher what each variable represents.

For example, consider the following code:

# Bad variable names
for i in range(10):
n = i * 2
print(n)

# Good variable names
for i in range(10):
doubled_number = i * 2
print(doubled_number)

In the first example, it’s not immediately clear what the variable n represents. Is it a count? A total? In the second example, the variable doubled_number clearly describes what the value represents, making it easier to understand the code.

Use whitespace effectively: Proper use of whitespace can help to improve the readability of your code by visually separating different blocks of code and making it easier to scan. Use blank lines to separate different sections of code, and use indentation to show the structure of your code. For example, you might use blank lines to separate different functions or to indicate the start and end of a loop. You might also use indentation to show that a block of code belongs to an if statement or a for loop.

For example, consider the following code:

# Bad use of whitespace
def calculate_total(items):
total = 0
for item in items:
total += item.price
return total

# Good use of whitespace
def calculate_total(items):
total = 0
for item in items:
total += item.price

return total

In the first example, there is no indentation to show the structure of the code, and the lack of blank lines makes it difficult to visually separate different sections of code. In the second example, the indentation clearly shows the structure of the code, and the blank lines help to visually separate the different parts of the function.

By using whitespace effectively, you can make your code easier to read and understand, which can save time and effort in the long run.

Follow PEP 8: PEP 8 is the official style guide for Python, and it includes a set of recommendations for formatting your code in a consistent and readable way. Some of the guidelines include using four spaces for indentation, limiting line lengths to 79 characters, and using lowercase letters and underscores for variable names. By following these guidelines, you can help to make your code more consistent and easier to read.

For example, consider the following code:

# Violating PEP 8 guidelines
def CalculateTotal(items):
Total = 0
for item in items:
Total += item.Price
return Total

# Following PEP 8 guidelines
def calculate_total(items):
total = 0
for item in items:
total += item.price
return total

In the first example, the function name, variable name, and attribute name all violate PEP 8 guidelines by using uppercase letters. In the second example, the names are all lowercase and use underscores, which follows the PEP 8 guidelines.

Use functions and modules: Breaking your code into smaller chunks by using functions and modules can help to make it more organized and easier to read. Functions should be defined to do one specific task, and they should have a clear and descriptive name that indicates what they do. Modules, on the other hand, can be used to organize related functions and variables. By breaking your code into smaller chunks and organizing it in this way, you can make it easier to find and reuse specific pieces of code.

For example, consider the following code:

# Bad organization
def calculate_total(items):
total = 0
for item in items:
total += item.price
return total

def calculate_discount(total, discount_percentage):
return total * (1 - discount_percentage)

# Good organization
def calculate_total(items):
total = 0
for item in items:
total += item.price
return total

def apply_discount(total, discount_percentage):
return total * (1 - discount_percentage)

In the first example, the function calculate_discount doesn't clearly indicate what it does, and it doesn't necessarily make sense in the context of the calculate_total function. In the second example, the function apply_discount clearly indicates what it does and how it relates to the calculate_total function.

Document your code: Proper documentation is important for making your code understandable to others (and to future you). Use comments to explain the purpose of your code and any non-obvious choices you made. You can also use docstrings to provide more detailed documentation for functions and modules. Docstrings are strings that appear at the beginning of a function or module and provide a summary of what the code does and how it can be used

# Bad documentation
def calculate_total(items):
total = 0
for item in items:
total += item.price
return total

# Good documentation
def calculate_total(items):
"""Calculate the total price of a list of items.

Args:
items (list): A list of Item objects.

Returns:
float: The total price of the items.
"""
total = 0
for item in items:
total += item.price
return total

This test function creates a list of Item objects with prices of 10 and 20, and then calls the calculate_total function to calculate the total price. It then uses an assert statement to verify that the calculated total is equal to 30. If the assert statement evaluates to True, the test will pass. If it evaluates to False, the test will fail and an error message will be displayed.

Unit tests like this one can be useful for testing individual functions or small pieces of code to ensure that they are working as intended. By writing and running a suite of unit tests, you can catch bugs and other issues early on in the development process and save time and effort in the long run.

# Unit test
def test_calculate_total():
items = [Item(price=10), Item(price=20)]
total = calculate_total(items)
assert total == 30

Test your code: Testing your code is an important step in the development process, as it can help you catch bugs and ensure that your code is working as intended. You can use unit tests to test individual functions and modules, and integration tests to test how different parts of your code work together. By testing your code, you can catch issues early on and save time and effort in the long run.

--

--