Skip to main content

Writing Clean Python: Comments, Docstrings, and PEP 8

Beginner15 min4 exercises90 XP
0/4 exercises

Imagine opening a cookbook where every recipe is scribbled in messy handwriting, with no labels, no ingredient lists, and no spacing between steps. You could figure it out eventually, but it would be painful. Code works the same way.

Professional developers spend far more time reading code than writing it. Studies suggest the ratio is about 10 to 1. That means making your code easy to read is one of the most valuable skills you can learn.

In this tutorial, you'll learn how to write Python that other people (and future you) will actually enjoy reading. We'll cover comments, docstrings, naming conventions, and PEP 8 — Python's official style guide.

Why Does Clean Code Matter?

Think about a messy bedroom. You know your stuff is in there somewhere, but finding anything takes forever. Clean code is like a tidy room — everything has a place, and you can find what you need quickly.

When you write code today and come back to it in two weeks, you'll have forgotten what half of it does. Clear, well-organized code acts like a map for your future self.

Clean code also matters when you work with others. On a team, everyone needs to understand everyone else's code. Messy code slows the whole team down.

Messy vs. clean code — same result, very different experience
Loading editor...

Both versions calculate the same thing. But Version B tells you what the code does without any extra explanation needed. The variable names are the documentation.

How to Write Good Comments in Python

You already know that comments start with # and Python ignores them. But knowing when and how to use comments is what separates beginner code from professional code.

A good comment explains why something is done, not what the code does. If your code is clear enough, the "what" should be obvious from reading it.

❌ Bad comments (explain the obvious)
# Set x to 5
x = 5

# Add 1 to x
x = x + 1

# Print x
print(x)
✓ Good comments (explain the why)
# Start with 5 retries (server sometimes drops first request)
retry_count = 5

# Move to next attempt
retry_count = retry_count + 1

print(retry_count)

Notice the difference? The bad comments just repeat what the code already says. The good comments tell you why the code exists and give context you can't get from the code alone.

When Should You Add Comments to Python Code?

Add a comment when the code does something surprising or non-obvious. If someone reading your code would say "wait, why?" — that's where a comment belongs.

Comments that actually help
Loading editor...

Also use comments for TODO notes — reminders about things you plan to fix or improve later. Most code editors highlight TODO comments to make them easy to find.

When Should You Avoid Comments?

If you feel the need to write a comment explaining what the code does, that's usually a sign the code itself should be clearer. Better variable names often eliminate the need for comments entirely.

❌ Comment hides unclear code
# Calculate the final price with 20% discount
p = x - (x * 0.2)
✓ Clear code needs no comment
discount_rate = 0.20
final_price = original_price - (original_price * discount_rate)

What Are Docstrings in Python?

A docstring is a special string that describes what a function, class, or module does. It goes right at the top of the function body, wrapped in triple quotes (""").

Think of a docstring as the instruction manual that comes with a product. You don't need to open the product to know what it does — you just read the manual.

A function with a proper docstring
Loading editor...

When you call help() on a function, Python displays its docstring. This is how built-in functions like print() and len() show their documentation too.

For short, simple functions, a one-line docstring is enough. For more complex functions, describe the arguments and what the function returns.

A simple one-line docstring
Loading editor...

Python Naming Conventions: How to Name Variables

Choosing good names is one of the hardest parts of programming. A great variable name is like a good label on a storage box — you know exactly what's inside without opening it.

Python uses a style called snake_case for variable and function names. Words are lowercase and separated by underscores.

Python naming conventions in action
Loading editor...

Here are the key naming conventions Python developers follow:

Naming conventions for different things
Loading editor...

How to Choose Meaningful Variable Names

A variable name should describe what the value represents, not what type it is. The goal is to make your code read like a sentence.

❌ Vague or cryptic names
x = "Alice"
n = 25
f = True
temp = 3
data = 98.6
my_list = ["math", "science"]
✓ Descriptive, meaningful names
student_name = "Alice"
student_age = 25
is_enrolled = True
max_attempts = 3
body_temperature = 98.6
course_list = ["math", "science"]

Single-letter names like x, n, and i are fine in short math formulas or tiny loops. But for anything else, use a real name that explains the purpose.

What Is PEP 8? Python Style Guide Basics

PEP 8 is Python's official style guide. PEP stands for "Python Enhancement Proposal," and number 8 is the one about coding style. It's like a dress code for Python code — everyone follows the same rules so all Python code looks familiar.

You don't need to memorize every rule. Here are the ones that matter most when you're starting out.

How to Use Indentation in Python (4 Spaces)

Python uses indentation to group code together. The standard is 4 spaces per level. Never mix tabs and spaces — pick one (spaces) and stick with it.

Proper 4-space indentation
Loading editor...

How to Use Blank Lines in Python Code

Blank lines are like paragraph breaks in an essay. They separate different ideas and make your code easier to scan.

Using blank lines to separate sections
Loading editor...

Use two blank lines before and after function definitions at the top level. Use one blank line to separate logical sections inside a function.

How to Use Spaces Around Operators in Python

Put a single space on each side of operators like =, +, -, ==, and !=. This makes your code much easier to read at a glance.

❌ No spaces (hard to read)
total=price*quantity+tax
is_valid=age>=18 and name!=""
result=x**2+y**2
✓ Spaces around operators (easy to read)
total = price * quantity + tax
is_valid = age >= 18 and name != ""
result = x**2 + y**2

Common Python Style Mistakes and How to Fix Them

Let's look at the most common style mistakes beginners make and how to fix them. These are small changes that make a big difference in readability.

❌ Comparing to True/False/None directly
if is_active == True:
    print("Active")

if result == None:
    print("No result")
✓ Use the Pythonic way
if is_active:
    print("Active")

if result is None:
    print("No result")

Don't compare to True or False with ==. Just use the variable directly. For None, always use is None instead of == None.

❌ Inconsistent style
userName = "Alice"      # camelCase
total_Price = 29.99     # mixed style
def CalculateTotal():   # PascalCase for function
    pass
✓ Consistent snake_case
user_name = "Alice"     # snake_case
total_price = 29.99     # snake_case
def calculate_total():   # snake_case
    pass

Pick a style and be consistent. In Python, that style is snake_case for variables and functions. Mixing styles makes your code look chaotic.

❌ Too many blank lines or none at all
def add(a, b):
    return a + b
def subtract(a, b):
    return a - b
def multiply(a, b):
    return a * b
✓ Two blank lines between functions
def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b

Python Linters: Tools That Check Your Style Automatically

You don't have to memorize every PEP 8 rule. Tools called linters can check your code for style problems automatically. Think of a linter as a spell-checker, but for code style.

Here are the most popular Python linters:

  • `flake8` — Checks for PEP 8 violations and common errors. Great for beginners.
  • `pylint` — More thorough. Gives suggestions about code quality too.
  • `ruff` — The new kid on the block. Very fast and combines many tools.
  • `black` — An auto-formatter. It doesn't just warn you — it fixes your style automatically.
  • Most code editors (like VS Code) can run linters in the background and underline style issues as you type. It's like having a style guide coach sitting next to you.


    Practice Exercises

    Time to practice! These exercises will help you build the habit of writing clean, readable Python code.

    Exercise 1: Add Comments and a Docstring
    Write Code

    Write a function called celsius_to_fahrenheit that takes a temperature in Celsius and returns the Fahrenheit value.

    The formula is: fahrenheit = celsius * 9/5 + 32

    Your function must include:

  • A docstring describing what it does
  • A comment explaining the formula
  • Then print the result of converting 100 degrees Celsius. The output should be:

    212.0
    Loading editor...
    Exercise 2: Fix the Bad Variable Names
    Fix the Bug

    This code works, but the variable names are terrible! No one can tell what x, y, z, and a mean.

    Rename the variables to be meaningful and use snake_case. The code calculates a worker's weekly pay. The output must stay exactly the same:

    Weekly pay: $450.0
    With overtime: $525.0
    Loading editor...
    Exercise 3: Rewrite Messy Code with PEP 8 Style
    Write Code

    The code below is messy. Rewrite it following PEP 8 rules:

    def calcArea(W,H):
      result=W*H
      return result
    def calcPerimeter(W,H):
      result=2*(W+H)
      return result
    w=8
    h=5
    print(f"Area: {calcArea(w,h)}")
    print(f"Perimeter: {calcPerimeter(w,h)}")

    Fix these issues:

  • Function names should be snake_case
  • Use 4 spaces for indentation
  • Add spaces around operators and after commas
  • Add two blank lines between function definitions
  • Use meaningful variable names
  • The output must be:

    Area: 40
    Perimeter: 26
    Loading editor...
    Exercise 4: Refactor — Clean Up This Code
    Refactor

    This function works but it's messy. Refactor it to be clean and professional:

    def d(p,r):
      a=p*r/100
      t=p-a
      return t
    print(d(200,15))

    Your refactored version must:

  • Give the function a meaningful name (it calculates a discounted price)
  • Use descriptive parameter names
  • Add a docstring explaining what the function does
  • Use proper PEP 8 spacing (4-space indent, spaces around operators)
  • Use two blank lines before the function call
  • The output must be:

    170.0
    Loading editor...

    Summary: What You Learned About Clean Python Code

    You now know the habits that separate beginner code from professional code. Here's a quick reference:
    ---------
    Comments (#)Explain why, not what# Texas tax rate (8.25%)
    Docstrings (""")Describe what a function does"""Convert Celsius to Fahrenheit."""
    Variable namesDescriptive, snake_casetotal_price, is_valid
    ConstantsUPPER_SNAKE_CASEMAX_SPEED = 120
    IndentationAlways 4 spacesdef greet(): then 4 spaces
    Blank lines2 between functionsSeparates logical sections
    OperatorsSpaces around =, +, etc.x = a + b
    PEP 8Python's official style guideConsistency is king

    Clean code isn't about being fancy. It's about being kind — to your teammates, to your future self, and to anyone who reads your code. Start building these habits now and they'll serve you for your entire programming career.

    What's Next?

    You've finished the Python Fundamentals section! You now have a solid foundation in Python basics. Next, you'll move into Control Flow — where you'll learn how to make your programs make decisions with if statements and repeat actions with loops.