Module 2 · Beginner · Python basics

Python comments and writing readable code

How to write Python comments and docstrings, good variable names, and PEP 8 style basics, with before-and-after examples that make your code easy to read.

By theprogrammers team · · 6 min read

Code is read far more often than it's written: by your teammates, by an interviewer looking at your GitHub, and by you, six weeks from now, when you've forgotten how it works. Python's own style guide puts it simply: readability counts.

This lesson covers comments, docstrings, naming, and the PEP 8 style rules every Python developer follows, with before-and-after examples. Good habits now will make every later lesson, and every job interview, easier.

Comments with

Python ignores everything from a # to the end of the line:

# Calculate the final price including GST
price = 500
gst_rate = 0.18    # 18% GST on this category
total = price * (1 + gst_rate)
  • A full-line comment explains the code below it.
  • An inline comment sits after code, separated by at least two spaces.
  • Python has no special multi-line comment. Put # at the start of each line; in VS Code, select the lines and press Ctrl + / to comment or uncomment them all.

Comment why, not what

A comment that repeats the code adds nothing:

count = count + 1    # add 1 to count

A good comment explains something the code can't say by itself: the reason:

count = count + 1    # include today, so a booking from the 1st to the 3rd is 3 days

If you need a comment to explain what some code does, try making the code clearer first, usually with better names.

Docstrings: documenting functions

A docstring is a string in triple quotes on the first line inside a function. It describes what the function does, and tools can read it: help(average) prints it, and VS Code shows it when you hover over the function.

def average(marks):
    """Return the mean of a non-empty list of numbers."""
    return sum(marks) / len(marks)

Longer docstrings can describe the arguments and return value:

def emi(principal, annual_rate, months):
    """Calculate the monthly instalment for a loan.

    principal: the loan amount in rupees
    annual_rate: yearly interest rate as a percentage, such as 9.5
    months: number of monthly payments
    """
    r = annual_rate / 12 / 100
    return principal * r * (1 + r) ** months / ((1 + r) ** months - 1)

A whole file can have a docstring too, as its first line. You'll write many more in Python functions.

Choose good names

Names are the most important documentation you write. Compare:

# Before
a = 1200
b = 0.18
c = a + a * b
# After
price = 1200
gst_rate = 0.18
total_price = price + price * gst_rate

The second version needs no comments at all.

Kind of nameStyleExample
Variables and functionssnake_casetotal_price, get_average()
ConstantsUPPER_CASEMAX_STUDENTS = 60
ClassesCapWordsBankAccount
BooleansRead like a yes/no questionis_valid, has_paid

Avoid single letters except for short loops (i, n) and coordinates (x, y). Avoid names that shadow built-in functions, such as list, sum, max or input: after sum = 10, the sum() function stops working in that file.

Replace magic numbers with constants

A "magic number" is an unexplained number in the code. What do 500 and 0.1 mean here?

if total > 500:
    total = total - total * 0.1

Named constants answer the question and keep each value in one place:

FREE_DELIVERY_LIMIT = 500
MEMBER_DISCOUNT = 0.1

if total > FREE_DELIVERY_LIMIT:
    total -= total * MEMBER_DISCOUNT

PEP 8: Python's style guide

PEP 8 is the official style guide for Python code. You don't need to memorise it; these rules cover most of it:

  • Indent with 4 spaces, never tabs.
  • Spaces around operators: total = price * qty, not total=price*qty.
  • A space after commas: print(a, b), not print(a,b).
  • No spaces inside brackets: print(x), not print( x ).
  • No spaces around = in keyword arguments: round(x, ndigits=2).
  • Keep lines short: under 79 characters is the official guideline; many teams allow 88 or 100.
  • Blank lines: two before and after a top-level function or class, one between methods, and single blank lines inside functions to separate steps.
  • Imports at the top of the file, one per line.

Here's a messy program and the same program in PEP 8 style:

# Before
def calc(l):
    t=0
    for x in l:t+=x
    return t/len(l)
print(calc([72,88,95]))
# After
def average(marks):
    """Return the mean of a list of marks."""
    total = 0
    for mark in marks:
        total += mark
    return total / len(marks)


print(average([72, 88, 95]))

Let tools do the formatting

Professional developers rarely format code by hand:

  • Formatters such as Black or Ruff rewrite your file in a consistent style when you save.
  • Linters such as Ruff or Pylint point out problems: unused variables, bad names, possible bugs.

In VS Code, install the Ruff or Black Formatter extension and turn on Format On Save in Settings. Every file you save is tidied automatically.

The Zen of Python

Type this in the Python REPL:

import this

It prints 19 short principles for writing Python, including "Beautiful is better than ugly", "Simple is better than complex" and "Readability counts". They're worth reading once.

Key takeaways

  • Use # comments to explain why; let clear code explain what.
  • Give functions a docstring in triple quotes.
  • Use descriptive snake_case names, UPPER_CASE constants and CapWords classes.
  • Follow PEP 8: 4-space indents, spaces around operators and after commas, short lines.
  • Let a formatter like Black or Ruff tidy your code automatically.

Practice

  1. Rewrite this code with clear names and a constant, and no comments.
x = 3
y = x * 24 * 60
print(y)
Show the answer
MINUTES_PER_DAY = 24 * 60

days = 3
total_minutes = days * MINUTES_PER_DAY
print(total_minutes)    # 4320
  1. Fix the PEP 8 problems in this line: def Area(l,w) :return l*w
Show the answer
def area(length, width):
    return length * width

Function names are lowercase snake_case, there's a space after the comma and none before the colon, the body goes on its own indented line, and the names say what they hold.

  1. Write a docstring for this function:
def is_even(n):
    return n % 2 == 0
Show the answer
def is_even(n):
    """Return True if n is even, otherwise False."""
    return n % 2 == 0
  1. Which comment is more useful, and why?
retries = 3    # set retries to 3
retries = 3    # the payment API often fails once at peak times
Show the answer

The second. The first repeats what the code already says. The second explains why the value exists, which a reader can't work out from the code.

Interview questions

What is PEP 8?

PEP 8 is Python's official style guide (Python Enhancement Proposal 8). It covers naming, indentation, line length, whitespace, imports and blank lines, so that Python code written by different people looks consistent.

What is the difference between a comment and a docstring?

A comment starts with #, is ignored by Python and is only visible in the source code. A docstring is a string literal as the first statement of a module, function or class; Python stores it in the __doc__ attribute, so help() and editors can show it.

How do you write multi-line comments in Python?

Put # at the start of each line. Triple-quoted strings are sometimes used, but they're actually string expressions, not comments; they only act as documentation when used as docstrings.

What naming conventions does Python use?

snake_case for variables, functions and modules, CapWords for classes, UPPER_CASE for constants, and a leading underscore, as in _helper, for names meant to be internal.

What to learn next

  1. Move on to decisions with Python if, elif and else, the start of the next module.
  2. Revisit the Python roadmap to see what's ahead.