Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 11 of 15

Code readability

Writing code people can understand: meaningful names, named constants instead of magic numbers, small functions, guard clauses instead of deep nesting, explaining why in comments, and simple over clever.

Beginner 8 min read·Lesson 289 of 306 in Python Programming

Learning objectives

  • Refactor unclear code into readable code
  • Replace magic numbers and deep nesting
  • Write comments that add information

Definition

Readable code communicates its intent clearly to human readers. It uses descriptive names, simple structure, small focused functions and comments that explain reasons rather than restating the code.

Introduction

'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.' Readability is what makes code maintainable.

Why it matters

You will read your own code months later, and teammates read it daily. Readable code is faster to change and has fewer bugs.

Detailed explanation

Names should say what something is or does: total_with_gst rather than f, students rather than l.

Replace magic numbers with named constants: SECONDS_PER_DAY = 24 * 60 * 60 explains itself.

Keep functions short and focused on one task; if you need 'and' to describe a function, consider splitting it.

Guard clauses handle special cases early and return, avoiding deeply nested if statements.

Prefer straightforward code over clever one-liners; a comprehension that needs a comment to explain it is too clever.

Comments should explain why (the business rule, the workaround, the reason for a choice), not repeat what the code obviously does.

Consistent formatting and structure let readers focus on logic instead of layout.

Refactor in small steps and re-run tests after each, so readability improvements never change behaviour.

Syntax

Python
SECONDS_PER_DAY = 24 * 60 * 60
def shipping_status(order):
if not order:
return "no order"
if not order["paid"]:
return "awaiting payment"
return "ship"
  • Descriptive names and constants.
  • Guard clauses instead of nesting.
  • Comments explain why.

Code examples

Named constants

Python
SECONDS_PER_DAY = 24 * 60 * 60
def days_to_seconds(days):
return days * SECONDS_PER_DAY
print(days_to_seconds(2))
Output
172800

Guard clauses instead of nesting

Python
def shipping_nested(order):
if order:
if order["paid"]:
if order["items"]:
return "ship"
else:
return "empty order"
else:
return "awaiting payment"
else:
return "no order"
def shipping(order):
if not order:
return "no order"
if not order["paid"]:
return "awaiting payment"
if not order["items"]:
return "empty order"
return "ship"
orders = [None, {"paid": False, "items": [1]}, {"paid": True, "items": []}, {"paid": True, "items": [1]}]
print([shipping(o) for o in orders] == [shipping_nested(o) for o in orders], [shipping(o) for o in orders])
Output
True ['no order', 'awaiting payment', 'empty order', 'ship']

More examples

Refactoring a cryptic function

Python
def f(l):
r = []
[r.append(x * 1.18) for x in l if x > 0]
return round(sum(r), 2)
GST_RATE = 0.18
def total_with_gst(prices, gst_rate=GST_RATE):
"""Total of the positive prices including GST."""
taxable = [p for p in prices if p > 0] # refunds (negative) are handled elsewhere
return round(sum(p * (1 + gst_rate) for p in taxable), 2)
prices = [100, -5, 250.5, 0]
print(f(prices), total_with_gst(prices))
Output
413.59 413.59

Step-by-step explanation

  • Both functions return the same result, so the refactor didn't change behaviour.
  • The new version names the rate, the data and the intermediate list.
  • The comment explains a business reason that the code alone can't show.

Expected output

Running “Refactoring a cryptic function” prints exactly:

TextOutput
413.59 413.59

Practical applications

  • Code reviews asking for clearer names before merging.
  • Onboarding new developers to an existing code base.

Best practices

  • Choose names that reveal intent.
  • Flatten logic with guard clauses.
  • Comment the why, not the what.

Common mistakes

Comments that repeat the code

Avoid

count += 1 # add one to count

Prefer

count += 1 # the header row isn't included in the export

Useful comments explain intent or context.

Clever one-liners

Avoid

r = [x for x in (y.strip() for y in s.split(",")) if x and not x.startswith("#")]

Prefer

parts = [p.strip() for p in s.split(",")]
r = [p for p in parts if p and not p.startswith("#")]

Two clear lines beat one puzzling line.

Important notes

  • 'Clean Code' and 'The Art of Readable Code' are popular books on this topic.

Key takeaways

  • Readable code uses clear names and constants.
  • Small functions and guard clauses simplify structure.
  • Comments explain reasons.

Try it yourself

  1. 1
    Refactor a nested if/else function from one of your projects using guard clauses.
  2. 2
    Find three magic numbers in your code and replace them with named constants.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Debugging, Testing and Best Practices” module. Answers and explanations are revealed after you submit.

  • AdvancedWhy shouldn't assert be used to validate user input?
  • AdvancedWhat is printed?
  • AdvancedWhere should you usually start reading a Python traceback?
Practise this module