Python 3D Academyবাংলা

Clean code: names, layout and PEP 8

🌍 In real life. Two recipes for the same biryani. One is a single long paragraph: "put thing 1 in the pot with the stuff, then the other stuff, cook for a while". The other has a title, a list of ingredients with amounts, and numbered steps. Both work, but only one can be followed by someone else, or by you next Eid.

Code is read far more often than it is written: by your teammates, by people learning from it, and by you in a month. Clean code is code written for those readers. Python even has an agreed style guide, PEP 8, so that all Python code looks familiar wherever you meet it.

The idea in one sentence: clean code is code a reader understands at first glance: names that say what things are, small functions that each do one job, and the layout every Python programmer expects (PEP 8).

Its words:

  • PEP 8: Python's official style guide for layout and names
  • snake_case: lower-case words joined by _, for variables and functions: total_price, bill_total
  • UPPER_CASE: for constants, values that never change: VAT_RATE; classes (Chapter 21) use PascalCase: BusTicket
  • magic number: an unexplained number in the middle of code, like * 1.15
  • linter and formatter: tools that check your style (ruff check) or rewrite your layout (ruff format, black)

Step by step, cleaning a messy function:

  1. Rename: f, l and t become bill_total, prices and subtotal.
  2. Name the magic numbers: 1.15 and 20 become VAT_RATE = 0.15 and SERVICE_CHARGE = 20, at the top.
  3. Split the jobs: adding VAT is one job, so it gets its own small function.
  4. Lay it out: 4 spaces per level, spaces around = and after commas, one statement per line.

Watch the clean version run. Every name tells you what its value means:

def f(l):
    t=0
    for i in l:t=t+i
    return t*1.15+20
print(f([100,60]))
The messy version gives the same 204.0. Python doesn't mind; your readers do. What are l and t? Why 1.15, why 20?

The PEP 8 basics. You don't need to learn the whole guide; these cover almost everything:

  • indent with 4 spaces, never tabs mixed with spaces
  • spaces around =, +, == and after commas: total = price * 2; none just inside brackets: max(a, b), not max( a,b ). Keyword arguments are the exception: round(x, ndigits=2), no spaces around that =
  • short lines: PEP 8 says 79 characters; many teams use 88 or 100
  • blank lines: two around each top-level function, so they stand apart
  • imports at the top of the file, one module per line
  • comparing with None: if seat is None, not == None (Lesson 13.4)

Tools do the boring part. On your own computer, pip install ruff, then ruff check . points out style problems and some likely bugs, and ruff format . rewrites the layout for you (black does the same). The Ruff extension for VS Code runs them every time you save. They don't run inside this browser app, so here, train your eye.

Small functions, one job each. If you need the word "and" to say what a function does ("reads the file and works out the total and prints the bill"), it is doing several jobs. Split it: each part gets a name, can be tested alone, and can be reused. A docstring (Lesson 14.5) says what a function gives back; a comment says why something is done, never just what the line already says.

def find_seat(seats, name):
    """Return the seat number booked by name, or None."""
    for number, booked_by in seats.items():
        if booked_by == name:
            return number
    return None


seats = {1: "Rahim", 2: "Mina"}
seat = find_seat(seats, "Mina")
if seat is not None:  # seat 0 would be falsy, so test for None itself
    print("Mina sits in seat", seat)
Clear names, a docstring, two blank lines after the function, is not None, and a comment that explains why.

What it costs. Nothing at all when the program runs: Python doesn't care what a name is called. It costs a few seconds of thought while writing, and saves minutes or hours every time someone reads the code.

Mistakes and edge cases.

  • One-letter names. i and j are fine as loop counters and x in a short lambda; elsewhere, say what the value is.
  • Names that lie. A variable called total that holds an average is worse than a vague name.
  • Using a built-in's name. After sum = 0, the line sum(prices) gives TypeError: 'int' object is not callable; after list = [1, 2], list("abc") gives TypeError: 'list' object is not callable. Pick total and items instead.
  • Mixing tabs and spaces. Python stops with TabError: inconsistent use of tabs and spaces in indentation. Set your editor to put 4 spaces when you press Tab.
  • Comments that repeat the code. count += 1 # add 1 to count tells the reader nothing; delete it, or say why the count goes up.

Quiz

  1. Which variable name follows PEP 8?

    • total_price
    • TotalPrice
    • totalPRICE
  2. A delivery app charges 60 taka for every order. How should the code hold that number?

    • DELIVERY_FEE = 60 at the top, used by name
    • Write 60 wherever it is needed
    • delivery_fee = 60 inside every function
  3. What does this print?

    VAT_RATE = 0.15
    
    
    def with_vat(price):
        return round(price * (1 + VAT_RATE), 2)
    
    
    print(with_vat(200))
  4. This prints 75 taka in all, then stops on the last line with TypeError: 'int' object is not callable. Which line causes it?

    prices = [40, 25, 10]
    sum = 0
    for p in prices:
        sum += p
    print(sum, "taka in all")
    average = sum(prices) / len(prices)
  5. What does a formatter like ruff format or black do?

    • Rewrites your code's layout to the standard style, without changing what it does
    • Finds and fixes the logic errors in your code
    • Makes your program run faster

Coding tasks

  1. This messy function works. Rewrite it as bill_total(prices) with a constant SERVICE_CHARGE = 20 at the top, a clear name for the running total, and PEP 8 layout. It must still add up the prices and add the service charge.

  2. Write is_snake_case(name): True when name is a PEP 8 variable name: not empty, made only of lower-case letters, digits and _, and not starting with a digit.