Basic Python: 2. Python Comments
Tags: python, beginners, programming, tutorial
Published: 2023-08-30 14:34:02

Comments in Python are annotations within your code that are ignored by the interpreter. They serve as notes to explain code logic, add reminders, or provide context to fellow developers (including your future self!).

### Table of Contents

1. **Single-Line Comments**
2. **Multi-Line Comments**
3. **Inline Comments**
4. **Documentation Strings (Docstrings)**
5. **Using Comments Effectively**
6. **Best Practices for Writing Comments**

### 1. Single-Line Comments

A single-line comment is a comment that spans only one line of code. It's preceded by the `#` symbol.

```python
# This is a single-line comment
print("Hello, world!")
```

### 2. Multi-Line Comments

While Python doesn't have a dedicated syntax for multi-line comments, you can achieve the same effect using triple quotes (`'''` or `"""`).

```python
"""
This is a multi-line comment.
It spans multiple lines and can be used
to explain complex code sections.
"""
```

### 3. Inline Comments

Inline comments are short comments placed at the end of a line of code to provide context or clarification.

```python
x = 5  # Initialize x to 5
```

### 4. Documentation Strings (Docstrings)

Docstrings are special multi-line comments used to document modules, functions, classes, or methods. They can be accessed using the `help()` function.

```python
def greet(name):
    """
    This function greets the user by name.
    """
    print(f"Hello, {name}!")

help(greet)
```

### 5. Using Comments Effectively

#### 1. Provide Context

```python
# Fetch user data from API (temporary mock data for example)
user_data = fetch_user_data(api_endpoint)
```

#### 2. Explanation of Complex Logic

```python
# Calculate the Fibonacci sequence using recursion
def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        # Calculate the sum of the previous two terms
        return fibonacci(n - 1) + fibonacci(n - 2)
```

#### 3. Clarification of Intent

```python
class Customer:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        # Initialize an empty list to store the customer's orders
        self.orders = []

    def place_order(self, order):
        # Add the order to the list of orders
        self.orders.append(order)
```

#### 4. TODO and FIXME Notes

```python
def calculate_tax(amount):
    # TODO: Implement tax calculation logic based on current tax rates
    return amount * 0.15

def fix_bug():
    # FIXME: There is an index out of bounds error in this code
    data = [1, 2, 3]
    value = data[3]
```

#### 5. Documentation of Algorithms

```python
def binary_search(arr, target):
    """
    Perform binary search on a sorted array.
    Args:
        arr: List[int], a sorted array
        target: int, the target element to find
    Returns:
        int, the index of the target element or -1 if not found
    """
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1
```

#### 6. External References

```python
# For more information about regular expressions, refer to the official documentation:
# https://docs.python.org/3/library/re.html
import re

pattern = r'\d+'  # Regular expression to match one or more digits
```

#### 7. Dealing with Workarounds

```python
def calculate_discount(price, discount_percent):
    if discount_percent < 0 or discount_percent > 100:
        # Workaround: Limit the discount percent to a valid range
        discount_percent = max(0, min(discount_percent, 100))
    
    discount_amount = (discount_percent / 100) * price
    final_price = price - discount_amount
    return final_price
```

### 6. Best Practices for Writing Comments

- **Keep Comments Updated**: If code changes, update the comments to match.
- **Be Concise**: Write clear and concise comments that deliver information efficiently.
- **Explain Logic, Not Syntax**: Focus on explaining why, not what the code does.
- **Maintain Consistency**: Follow a consistent style for commenting.
- **Avoid Redundancy**: Comments should add value, not repeat what's obvious from the code itself.
- **Use Meaningful Variable Names**: Good variable names reduce the need for excessive commenting.
- **Use Proper Grammar and Spelling**: Maintain professionalism by writing error-free comments.
- **Review and Refactor**: Regularly review your code and refactor as needed to maintain clear and relevant comments.