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
# Calculate total price
price = 10
quantity = 3
total = price * quantity
Python ignores comments when running code.
Good Comments Explain Why
Good:
# Apply discount for premium users
price = price * 0.9
Less useful:
# 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
def add(a, b):
"""Return the sum of two numbers."""
return a + b
Class Example
class User:
"""Represent a user account."""
Why Docstrings Help
They explain:
- purpose
- parameters
- return value
- usage
Better Function Example
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:
total_price = price * quantity
Instead of:
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:
def area(w, h):
return w * h
Expected improved version:
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
- What symbol starts a comment?
- What is a docstring?
- Why are comments useful?
- 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.