Skip to main content
Editor

Writing Clean Python: Comments, Docstrings, and PEP 8

Beginner15 min4 exercises90 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

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. Robert C. Martin, author of the book Clean Code, puts the ratio at well over 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
# Which version would you rather read?
# Version A
x = 3.14159
y = 10
z = x * y * y
print(z)
# Version B
pi = 3.14159
radius = 10
circle_area = pi * radius * radius
print(f"Area of circle: {circle_area}")
Output
314.159
Area of circle: 314.159

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
# Good reasons to comment:
price = 9.99
tax = price * 0.0825 # Texas sales tax rate (8.25%)
# Multiply by 100 to avoid floating-point rounding errors
price_in_cents = int(price * 100)
# TODO: Replace with database lookup once API is ready
user_name = "Guest"
Output
(no output)

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
def calculate_tip(bill_amount, tip_percent):
"""Calculate the tip amount for a restaurant bill.
Args:
bill_amount: The total bill in dollars.
tip_percent: The tip percentage (e.g., 20 for 20%).
Returns:
The tip amount in dollars.
"""
return bill_amount * (tip_percent / 100)
# Using the function
tip = calculate_tip(50.00, 20)
print(f"Tip: ${tip:.2f}")
# You can view any function's docstring with help()
help(calculate_tip)
Output
Tip: $10.00
Help on function calculate_tip in module __main__:

calculate_tip(bill_amount, tip_percent)
    Calculate the tip amount for a restaurant bill.

    Args:
        bill_amount: The total bill in dollars.
        tip_percent: The tip percentage (e.g., 20 for 20%).

    Returns:
        The tip amount in dollars.

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
# Simple function - one-line docstring is fine
def square(n):
"""Return the square of a number."""
return n * n
print(square(7))
print(square(12))
Output
49
144

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
# snake_case - the Python way
user_name = "Alice"
total_price = 29.99
is_logged_in = True
max_retry_count = 3
# Use these in practice
print(f"User: {user_name}")
print(f"Total: ${total_price}")
print(f"Logged in: {is_logged_in}")
print(f"Max retries: {max_retry_count}")
Output
User: Alice
Total: $29.99
Logged in: True
Max retries: 3

Here are the key naming conventions Python developers follow:

Naming conventions for different things
# Variables and functions: snake_case
player_score = 100
def calculate_average(numbers):
"""Return the average of a list of numbers."""
return sum(numbers) / len(numbers)
# Constants: UPPER_SNAKE_CASE
MAX_SPEED = 120
PI = 3.14159
DATABASE_URL = "localhost:5432"
# Classes: PascalCase (you'll learn classes later)
# class PlayerCharacter:
# class ShoppingCart:
print(f"Player score: {player_score}")
print(f"Max speed: {MAX_SPEED}")
print(f"Pi: {PI}")
Output
Player score: 100
Max speed: 120
Pi: 3.14159

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
# Correct: 4 spaces for each indentation level
def greet(name):
"""Print a greeting message."""
if name:
message = f"Hello, {name}!"
print(message)
else:
print("Hello, stranger!")
greet("Alice")
greet("")
Output
Hello, Alice!
Hello, stranger!

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
# Two blank lines before a function definition
def calculate_area(width, height):
"""Calculate the area of a rectangle."""
return width * height
def calculate_perimeter(width, height):
"""Calculate the perimeter of a rectangle."""
return 2 * (width + height)
# Use the functions
area = calculate_area(5, 3)
perimeter = calculate_perimeter(5, 3)
print(f"Area: {area}")
print(f"Perimeter: {perimeter}")
Output
Area: 15
Perimeter: 16

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, plus one formatter:

  • 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 - Not a linter but an auto-formatter. Instead of warning 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
  • Return the value without printing it: the checks call your function and print what it returns. For 100 degrees Celsius that is:

    212.0
    # Write your function with a docstring and comment
    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, a, and b 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: $562.5
    x = 15.0
    y = 30
    z = x * y
    a = 5
    b = x * 1.5 * a
    print(f"Weekly pay: ${z}")
    print(f"With overtime: ${z + b}")
    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
    # Rewrite the messy code from the instructions above, following PEP 8 rules
    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
    # Refactor the messy code into clean, professional Python

    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:

    ConceptKey RuleExample
    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.

    Harder problems

    More problems on this topic: Python idioms

    Related Tutorials

    Was this tutorial helpful?