Skip to content

[BEGINNER] Add Docstrings and Comments to All Functions #2300

@hackdartstorm

Description

@hackdartstorm

📋 The Real Problem

What's Wrong:

Our code has NO docstrings. No comments explaining WHY. No documentation for functions.

Look at any file in this repository:

# basics/04_functions/functions.py
def add():
    a = int(input("Enter the Number: "))
    b = int(input("Enter the Number: "))
    sum = a + b
    print(sum)

What's Missing:

# What we SHOULD have:
def add():
    """
    Get two numbers from user and print their sum.
    
    This function demonstrates:
    - User input with validation
    - Type conversion (string to int)
    - Basic arithmetic operations
    
    Returns:
        None (prints result directly)
    
    Example:
        >>> add()
        Enter the Number: 5
        Enter the Number: 3
        8
    """
    a = int(input("Enter the Number: "))
    b = int(input("Enter the Number: "))
    sum = a + b
    print(f"Sum: {sum}")

Why This Issue Exists:

Beginner tutorials often skip documentation to "keep it simple." But this teaches students that documentation is optional. It's not.


💡 Why This Matters

1. Learning to Read Code

Reality check: Professional programmers spend more time READING code than WRITING it.

Without docstrings, students learn:

  • ❌ "Code is self-documenting" (it's not)
  • ❌ "I'll figure it out by reading the code" (wastes time)
  • ❌ "Documentation is for later" (later never comes)

With docstrings, students learn:

  • ✅ "Good code explains itself"
  • ✅ "Save time by reading docs first"
  • ✅ "Documentation is part of coding"

2. Real-World Preparation

What happens in industry:

Scenario Without Docs With Docs
New team member joins Weeks to understand code Days to understand code
Fixing bugs Guess what function does Read docstring, understand
Adding features Afraid to change code Confident about changes
Code review "What does this do?" "Docstring explains it"

We should prepare students for the real world.

3. Code Maintenance

Without documentation:

# 6 months later, original author returns:
def calculate(a, b, c):
    return (a * b) + c / 2 - (b % 3)

# Author thinks: "What was I thinking? What does this do?"

With documentation:

def calculate_interest(principal, rate, months):
    """
    Calculate compound interest with monthly compounding.
    
    Formula: (principal × rate) + months / 2 - (rate % 3)
    
    Args:
        principal: Initial investment amount
        rate: Annual interest rate (as percentage)
        months: Investment duration in months
    
    Returns:
        Total interest earned
    
    Example:
        >>> calculate_interest(1000, 5, 12)
        5029.5
    """
    return (principal * rate) + months / 2 - (rate % 3)

4. Accessibility

Good documentation helps:

  • Non-native English speakers - Clear explanations help
  • Visual learners - Examples in docstrings help understanding
  • Students with learning disabilities - Structured information helps
  • Everyone - Saves time, reduces confusion

🎯 What You'll Do

Task 1: Choose a File to Document

Start with ONE of these simple files:

File Functions Difficulty Priority
basics/02_variables_types/01_arithmetic.py 1 function ⭐ Easy High
basics/04_functions/functions.py 3 functions ⭐⭐ Medium High
basics/03_control_flow/02_check_prime.py 1 function ⭐⭐ Medium Medium

Task 2: Learn Docstring Format

Python has a standard docstring format:

def function_name(param1, param2):
    """
    One-line summary of what function does.
    
    Longer description if needed. Explain WHY, not just WHAT.
    
    Args:
        param1: Description of first parameter
        param2: Description of second parameter
    
    Returns:
        Description of return value
    
    Raises:
        ValueError: When parameter is invalid
    
    Example:
        >>> function_name(5, 10)
        15
    """
    # Function code here

Task 3: Add Docstrings to Your Chosen File

Before:

# basics/02_variables_types/01_arithmetic.py

def add():
    a = int(input("Enter the Number : "))
    b = int(input("Enter the Number : "))
    add = a + b
    print(add)

After:

# basics/02_variables_types/01_arithmetic.py

def add():
    """
    Get two numbers from user and print their sum.
    
    This function demonstrates basic arithmetic operations
    and user input handling in Python.
    
    Input:
        Prompts user for two numbers
    
    Output:
        Prints the sum of the two numbers
    
    Example:
        >>> add()
        Enter the Number : 5
        Enter the Number : 3
        8
    
    Note:
        This function does not handle invalid input.
        Enter only whole numbers.
    """
    a = int(input("Enter the Number : "))
    b = int(input("Enter the Number : "))
    sum_result = a + b  # Renamed from 'add' to avoid confusion
    print(f"Sum: {sum_result}")

Task 4: Add Inline Comments for Complex Logic

Before:

# basics/03_control_flow/02_check_prime.py

def is_prime(num):
    if num <= 1:
        return False
    elif num == 2:
        return True
    else:
        for i in range(2, int(num * 0.5) + 1):
            if num % i == 0:
                return False
        return True

After:

# basics/03_control_flow/02_check_prime.py

def is_prime(num):
    """
    Check if a number is prime.
    
    A prime number is a natural number greater than 1
    that has no positive divisors other than 1 and itself.
    
    Args:
        num: The number to check
    
    Returns:
        True if num is prime, False otherwise
    
    Example:
        >>> is_prime(7)
        True
        >>> is_prime(10)
        False
    """
    # Numbers less than or equal to 1 are not prime
    if num <= 1:
        return False
    
    # 2 is the only even prime number
    elif num == 2:
        return True
    
    else:
        # Check divisibility from 2 up to half of num
        # We only need to check up to num/2 because a larger
        # factor would require a corresponding smaller factor
        for i in range(2, int(num * 0.5) + 1):
            # If num is divisible by i, it's not prime
            if num % i == 0:
                return False
        
        # If no divisors found, num is prime
        return True

Task 5: Review Your Documentation

Ask yourself:

  1. Could a beginner understand this?

    • Show it to a friend who's learning Python
    • If they're confused, rewrite it
  2. Does it explain WHY, not just WHAT?

    • Bad: # Add two numbers
    • Good: # Calculate sum for total score calculation
  3. Are there examples?

    • Examples are worth 1000 words of explanation
  4. Is formatting consistent?

    • Use the same style across all docstrings

✅ What Success Looks Like

Before (Current State)

def calculate(a, b):
    return a * b + a / b

Student reads this and thinks:

  • "What does this calculate?"
  • "What are a and b?"
  • "When would I use this?"
  • "What if b is zero?"

After (Expected State)

def calculate_total_price(unit_price, quantity):
    """
    Calculate total price with bulk discount.
    
    Applies a 10% discount when quantity is 10 or more.
    
    Args:
        unit_price: Price per unit (must be positive)
        quantity: Number of units (must be positive)
    
    Returns:
        Total price after applying any discounts
    
    Raises:
        ValueError: If price or quantity is negative
    
    Example:
        >>> calculate_total_price(10.0, 5)
        50.0
        >>> calculate_total_price(10.0, 15)
        135.0  # 10% discount applied
    """
    if unit_price < 0 or quantity < 0:
        raise ValueError("Price and quantity must be positive")
    
    base_price = unit_price * quantity
    
    # Apply 10% bulk discount for orders of 10 or more
    if quantity >= 10:
        return base_price * 0.9
    
    return base_price

Student reads this and thinks:

  • "Oh, it calculates prices with discounts!"
  • "a is unit_price, b is quantity"
  • "I'd use this for a shopping cart"
  • "It handles negative numbers - good!"

Code Quality Improvements

After this fix:

  • All functions have docstrings
  • Complex logic has inline comments
  • Examples included in docstrings
  • Parameters are described
  • Return values are described
  • Edge cases are documented
  • Consistent format across all files

📚 Additional Context & References

Files That Need Documentation

Priority list:

basics/02_variables_types/
├── 01_arithmetic.py          ⭐ Add docstrings
├── 05_square_input.py        ⭐ Add docstrings
└── 12_celsius_fahrenheit.py  ⭐ Add docstrings

basics/03_control_flow/
├── 02_check_prime.py         ⭐⭐ Add docstrings + comments
└── 16_simple_calculator.py   ⭐⭐ Add docstrings + comments

basics/04_functions/
└── functions.py              ⭐⭐⭐ Add comprehensive docs

Docstring Styles

Google Style (recommended for beginners):

def function(param1, param2):
    """Summary of function.
    
    Args:
        param1: Description of param1
        param2: Description of param2
    
    Returns:
        Description of return value
    """

NumPy Style:

def function(param1, param2):
    """Summary of function.
    
    Parameters
    ----------
    param1 : type
        Description of param1
    param2 : type
        Description of param2
    
    Returns
    -------
    type
        Description of return value
    """

reStructuredText (used by Sphinx):

def function(param1, param2):
    """Summary of function.
    
    :param param1: Description of param1
    :type param1: type
    :param param2: Description of param2
    :type param2: type
    :returns: Description of return value
    :rtype: type
    """

Pick ONE style and use it consistently throughout the project.

Helpful Resources

Python Documentation:

Style Guides:

Tools:

Common Documentation Mistakes

Mistake 1: Restating the obvious

# BAD
def add(a, b):
    """Add a and b."""  # This is obvious from the function name!
    return a + b

# GOOD
def add(a, b):
    """Add two numbers with overflow protection."""  # Explains WHY
    return a + b

Mistake 2: No examples

# BAD
def calculate_compound_interest(principal, rate, time):
    """Calculate compound interest.
    
    Args:
        principal: Principal amount
        rate: Interest rate
        time: Time period
    """
    # ... code ...

# GOOD
def calculate_compound_interest(principal, rate, time):
    """Calculate compound interest.
    
    Args:
        principal: Initial investment amount
        rate: Annual interest rate (as decimal, e.g., 0.05 for 5%)
        time: Investment period in years
    
    Returns:
        Total amount after compound interest
    
    Example:
        >>> calculate_compound_interest(1000, 0.05, 10)
        1628.89
    """
    # ... code ...

Mistake 3: Outdated documentation

# Code changes but docstring doesn't:
def calculate(a, b):
    """Multiply a and b."""  # But code now adds them!
    return a + b  # Documentation is WRONG

Solution: Update documentation EVERY time you change the code.

When to Add Comments

DO add comments for:

# WHY, not WHAT
if temperature > 100:
    # Water boils at 100°C at sea level
    state = "gas"

# Workarounds for bugs
result = value * 2
# TODO: Fix this when library updates to v2.0
# See: https://github.com/example/issue/123

# Complex algorithms
# Using binary search for O(log n) performance
# See: https://en.wikipedia.org/wiki/Binary_search_algorithm

DON'T add comments for:

# Obvious code
x = x + 1  # Add 1 to x  (DON'T do this!)

# What the code does (instead explain WHY)
if user.is_admin():  # If user is admin (DON'T do this!)
    grant_access()

🎯 Acceptance Criteria

This issue is complete when:

  • At least 10 files have comprehensive docstrings
  • All functions in those files are documented
  • Parameters are described with types
  • Return values are described
  • Examples are included in docstrings
  • Complex logic has inline comments explaining WHY
  • Consistent style used across all docstrings
  • No outdated documentation (matches current code)
  • Beginner tested - a student could understand the code from docs alone

🏆 Bonus Challenges

⭐ Add Type Hints

Add type hints along with docstrings:

def add(a: int, b: int) -> int:
    """Add two integers.
    
    Args:
        a: First number
        b: Second number
    
    Returns:
        Sum of a and b
    """
    return a + b

⭐⭐ Generate Documentation Automatically

Use Sphinx to generate HTML documentation:

pip install sphinx
sphinx-quickstart docs/
sphinx-apidoc -o docs/ basics/
cd docs/
make html

⭐⭐⭐ Add Documentation Tests

Test that examples in docstrings actually work:

import doctest
import basics.02_variables_types.01_arithmetic

# Run doctests
doctest.testmod(basics.02_variables_types.01_arithmetic)

⭐⭐⭐⭐ Add Documentation Quality Checks

Use pydocstyle to enforce docstring standards:

pip install pydocstyle
pydocstyle basics/

Ready to make our code self-documenting? Start contributing! 🚀

Questions? Ask in the comments below!

Metadata

Metadata

Assignees

No one assigned

    Labels

    beginner-friendlyGood for beginnerscode-qualityCode quality improvementsdocumentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions