Want to write better code?

Clean Code in Python: Good vs. Bad Practices Examples

Improve Python Code Quality with Clean Coding Practices!

CyCoderX
Python’s Gurus

--

Photo by Steinar Engeland on Unsplash

As a developer with over four years of experience, I have cultivated a deep passion for Python and its infinite capabilities. Python’s versatility and simplicity make it a go-to language for data engineering tasks, enabling developers to streamline complex processes with ease.

Throughout my journey, I regularly share insights on Python programming, from beginner tips to advanced techniques, helping others enhance their coding skills and stay abreast of the latest trends.

In this guide, we’ll delve deeper into the concept of “Clean Code” in Python by contrasting examples of good and bad practices. This comparison will illustrate how clean code principles can transform code from being hard to maintain and understand to being clear and efficient.

Please consider following me for more updates and insights; your support helps me continue creating valuable content

Why Clean Code Matters

Writing clean code is essential for several reasons:

  • Maintainability: Clean code is easier to read, understand and maintain.
  • Scalability: Well-structured code can be scaled and extended more easily.
  • Collaboration: Clean code is more approachable for other developers, facilitating teamwork and code reviews.
  • Debugging: Errors and bugs are easier to spot and fix in clean code.

Are you also interested in SQL content? Click here to check out my list on Medium.

Examples of Bad Practices vs. Good Practices

Example 1: Variable and Function Names

Bad Practice:

def calc(a, b, c):
return a + b - c

In this example, the names of the variables and function are nondescriptive. It’s unclear what each variable represents or what the function does.

Good Practice:

def calculate_final_score(base_score, bonus_points, penalty):
return base_score + bonus_points - penalty

This code uses descriptive names, making it much clearer and more readable.

Example 2: Single Responsibility Functions

Bad Practice:

def process_data(data):
# Filter data
data = [x for x in data if x > 0]

# Calculate average
average = sum(data) / len(data)

# Print results
print(f"Average: {average}")
return data

Here, process_data is doing too much: filtering data, calculating an average and printing results.

Good Practice:

def filter_positive_data(data):
return [x for x in data if x > 0]

def calculate_average(data):
return sum(data) / len(data)

def print_results(average):
print(f"Average: {average}")

data = filter_positive_data(raw_data)
average = calculate_average(data)
print_results(average)

Dividing the functionality into three separate functions improves clarity and code reusability.

Example 3: Error Handling

Bad Practice:

def divide_numbers(x, y):
return x / y

This code does not handle the possibility of dividing by zero, which could lead to uncaught errors.

Good Practice:

def divide_numbers(x, y):
if y == 0:
raise ValueError("Cannot divide by zero.")
return x / y

Here, the code proactively handles the possibility of an error, avoiding potential problems.

Example 4: Duplicated Code

Bad Practice:

def show_details(product):
print(f"Name: {product['name']}")
print(f"Price: {product['price']}")
print(f"Category: {product['category']}")

def show_summary(product):
print(f"Name: {product['name']}")
print(f"Price: {product['price']}")

In this example, printing product details is duplicated in two functions.

Good Practice:

def print_product_info(product, details=False):
print(f"Name: {product['name']}")
print(f"Price: {product['price']}")
if details:
print(f"Category: {product['category']}")

# Usage:
print_product_info(product, details=True)
print_product_info(product)

The function print_product_info eliminates duplication and allows for greater flexibility.

Your engagement, whether through claps, comments, or following me, fuels my passion for creating and sharing more informative content.
If you’re interested in more
Python content, please consider following me. Alternatively, you can click here to check out my Python list on Medium.

Additional Tips for Writing Clean Code

1. Consistent Naming Conventions

Stick to a consistent naming convention throughout your code. This can be camelCase, snake_case, or any other convention, but it should be uniform.

2. Use Comments Wisely

Comments should be used to explain why something is done, not what is done. The code itself should be self-explanatory if it follows clean coding principles.

3. Avoid Magic Numbers

Replace magic numbers with named constants to make your code more readable and maintainable.

# Bad Practice
area = length * 3.14

# Good Practice
PI = 3.14
area = length * PI

4. Keep Functions Short

Each function should do one thing and do it well. If a function is getting too long, consider breaking it down into smaller functions.

5. Write Unit Tests

Unit tests help ensure your code works as expected and make it easier to spot and fix bugs. They also serve as documentation for your code.

6. Follow PEP 8

PEP 8 is the style guide for Python code. Following these guidelines helps keep your code consistent and readable.

Photo by Jen Theodore on Unsplash

Conclusion

These examples show how “Clean Code” practices can significantly improve the clarity, efficiency and maintainability of Python code. Adopting these principles not only makes the code easier to work with for you and others but also teaches discipline and attention to detail, valuable skills for any programmer.

By embracing clean code practices, you can write Python code that is not only functional but also elegant and easy to maintain. Whether you’re working on a solo project or collaborating with a team, clean code is the key to success.

Final Words:

Thank you for taking the time to read my article.

Hey There! I’m Charilaos Alkiviades Savoullis, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, Databases, AI, Data Engineering, lifestyle and more!

For similar articles and updates, feel free to explore my Medium profile https://medium.com/@casavoullis

If you enjoyed this article, consider liking and following for future updates.
Join me as we explore the exciting world of
tech, data and beyond!

This article was first published on medium by Charilaos Savoullis.

Don’t hesitate to connect with me on my socials:

LinkedIn: https://bit.ly/3UK8KNk
GitHub: https://bit.ly/3WrMzgm

Interested in more Python content and tips? Click here to find out more!

How about Databases and SQL content? Click here to find out more!

Let me know in the comments below … or above, depending on your device 🙃

Python’s Gurus🚀

Thank you for being a part of the Python’s Gurus community!

Before you go:

  • Be sure to clap x50 time and follow the writer ️👏️️
  • Follow us: Newsletter
  • Do you aspire to become a Guru too? Submit your best article or draft to reach our audience.

--

--

CyCoderX
Python’s Gurus

Data Engineer | Python & SQL Enthusiast | Cloud & DB Specialist | AI Enthusiast | Lifestyle Blogger | Simplifying Big Data and Trends, one article at a time.