CodingNic

Testing and Best Practices

Documentation and Comments

Testing and Best Practices 32 min read

Documentation and Comments

Documentation and Comments

Good code should be understandable.

Sometimes other people will read your code.

Sometimes future you will read your own code.

Documentation and comments help explain what code does and how to use it.

Why This Matters

Documentation helps you:

  • understand code later
  • work with teams
  • use functions correctly
  • maintain projects faster

Comments

Comments are notes inside code.

Python comments start with #.

Example

python
# Calculate total price
price = 10
quantity = 3
total = price * quantity

Python ignores comments when running code.

Good Comments Explain Why

Good:

python
# Apply discount for premium users
price = price * 0.9

Less useful:

python
# Multiply price by 0.9
price = price * 0.9

The code already shows that.

Docstrings

A docstring is a string used to describe a function, class, or module.

It is written inside triple quotes.

Function Example

python
def add(a, b):
    """Return the sum of two numbers."""
    return a + b

Class Example

python
class User:
    """Represent a user account."""

Why Docstrings Help

They explain:

  • purpose
  • parameters
  • return value
  • usage

Better Function Example

python
def greet(name):
    """
    Return a greeting message.

    name: user's name
    """
    return "Hello " + name

Readability Matters Too

Good names reduce the need for many comments.

Better:

python
total_price = price * quantity

Instead of:

python
x = price * quantity

Avoid Too Many Comments

Do not comment every obvious line.

Use comments only when helpful.

Code Along

Add a docstring to a square(n) function.

Mini Challenge

Improve this code with comments or docstrings:

python
def area(w, h):
    return w * h

Expected improved version:

python
def area(width, height):
    """Return rectangle area."""
    return width * height

Real World Use Case

Teams use documentation for APIs, libraries, business systems, and open-source projects.

Quiz

  1. What symbol starts a comment?
  2. What is a docstring?
  3. Why are comments useful?
  4. Why use clear names too?

Assignment

Choose one old file and add comments plus docstrings to at least two functions.

Summary

You learned how comments and docstrings make Python code easier to understand and maintain.