SwadhyAI Notes

All Python notes

Python Comments 💬

Why use comments?

Comments are lines in your code that are ignored by the interpreter. They are crucial for:

  • Explaining complex logic.
  • Making code more readable for others (and your future self!).
  • Temporarily disabling code during testing (debugging).

✨ Single Line Comments

Comments start with a # symbol. Anything after the hash on that line is ignored.

python
# This is a comment
print("Hello, World!")

📍 Inline Comments

You can place comments at the end of a line of code.

python
x = 5  # This is an inline comment

⚠️ Best Practice

Inline comments should be separated by at least two spaces from the statement. They should be used sparingly.

📚 Multi-line Comments

Python doesn't have a specific syntax for multi-line comments like /* ... */ in Java or C++. You have two options:

Option 1: Multiple Hash Marks

python
# This is a comment
# written in
# more than just one line
print("Hello, World!")

Option 2: String Literals (Docstrings)

Since Python ignores string literals that aren't assigned to a variable, you can use triple quotes (""") for multi-line comments. This is technically a string, but acts as a comment.

python
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

📝 Docstrings vs Comments

Docstrings (Documentation Strings) are a special type of comment used to document modules, classes, functions, and methods. They must be the first statement in the object's definition.

python
def add(a, b):
    """
    This function adds two numbers and returns the result.
    
    Parameters:
    a (int): The first number
    b (int): The second number
    """
    return a + b

print(add.__doc__)  # You can access the docstring programmatically!

✨ Pro Tip: Explain "Why", not "What"

Good code explains what it does. Good comments explain why it does it.
❌ x = x + 1 # Increment x (Redundant)
✅ x = x + 1 # Adjust for zero-based indexing (Helpful)

✨ Pro Tip: TODO Comments

Developers often use # TODO: to mark areas where code needs to be added or fixed later. Many IDEs highlight these automatically.

python
def complex_algorithm():
    # TODO: Optimize this function for large datasets
    pass