Writing Clean Python: Comments, Docstrings, and PEP 8
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.
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.
# Set x to 5
x = 5
# Add 1 to x
x = x + 1
# Print x
print(x)# 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.
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.
# Calculate the final price with 20% discount
p = x - (x * 0.2)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.
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.
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.
Here are the key naming conventions Python developers follow:
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.
x = "Alice"
n = 25
f = True
temp = 3
data = 98.6
my_list = ["math", "science"]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.
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.
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.
total=price*quantity+tax
is_valid=age>=18 and name!=""
result=x**2+y**2total = price * quantity + tax
is_valid = age >= 18 and name != ""
result = x**2 + y**2Common 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.
if is_active == True:
print("Active")
if result == None:
print("No result")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.
userName = "Alice" # camelCase
total_Price = 29.99 # mixed style
def CalculateTotal(): # PascalCase for function
passuser_name = "Alice" # snake_case
total_price = 29.99 # snake_case
def calculate_total(): # snake_case
passPick a style and be consistent. In Python, that style is snake_case for variables and functions. Mixing styles makes your code look chaotic.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * bdef add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * bPython 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:
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.
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:
Then print the result of converting 100 degrees Celsius. The output should be:
212.0This 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.0The 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:
The output must be:
Area: 40
Perimeter: 26This 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:
The output must be:
170.0Summary: 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 names | Descriptive, snake_case | total_price, is_valid |
| Constants | UPPER_SNAKE_CASE | MAX_SPEED = 120 |
| Indentation | Always 4 spaces | def greet(): then 4 spaces |
| Blank lines | 2 between functions | Separates logical sections |
| Operators | Spaces around =, +, etc. | x = a + b |
| PEP 8 | Python's official style guide | Consistency 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.