Course contentsShow
← Python
Lesson 10 of 1,0601. Foundations and EnvironmentFree lesson

Writing Comments and Documenting Code Logic

You will learn how to annotate your scripts with comments to explain complex logic while ensuring the interpreter ignores these descriptive notes.

In this lesson, you will learn how to leave descriptive notes in your scripts so that both you and other developers can understand your logic without affecting how the computer runs your code.

The Power of the Hash Symbol

When you write a Python script, the interpreter executes every line it sees. However, there is a special character that acts as a "stop sign" for the interpreter: the hash symbol (#).

Whenever you place a # in your code, Python ignores everything that follows it on that same line. This allows you to add human-readable text directly into your source files without triggering syntax errors or impacting the program's output.

Putting Comments to Use

Comments are not for the computer; they are for the human reading the code. Use them to explain why you made a specific design choice, or to clarify a complex logic block.

# Calculate the total price including a 5% tax
price = 100
tax = 0.05
total = price + (price * tax)  # This logic handles the tax calculation

print(total)

In the example above, the interpreter completely skips the text after the #. If you were to remove the hash symbol, the interpreter would try to read "Calculate the total..." as if it were actual Python code, which would cause the program to crash.

Best Practices for Documentation

  1. Be Concise: Don't explain what is obvious (e.g., don't write # add 1 to x next to x += 1). Instead, explain the intent.
  2. Keep Them Updated: If you change your code logic but forget to update your comment, the comment can become misleading. Always keep your notes in sync with your instructions.
  3. Use Them for Debugging: If you suspect a specific line is causing an error, you can "comment it out" by placing a # at the start of the line. This prevents that line from executing without you having to delete it permanently.

By effectively documenting your code, you create a "roadmap" that makes your scripts much easier to maintain as your projects grow in complexity.

Key Takeaway: Comments allow you to add human-friendly explanations to your code by using the # symbol, which instructs the Python interpreter to ignore the text that follows.