Python ยท Chapter 4 of 45
Python Comments
Comments are ignored by the interpreter. They exist so humans can explain what code does.
Python supports single-line comments starting with `#`. There is no true multi-line comment syntax โ programmers use triple-quoted strings for that purpose.
Single-line comments
Anything after `#` on a line is a comment. Use them to explain intent, not restate what code already says.
Docstrings
Triple-quoted strings placed at the start of a module, function or class are called docstrings. Tools like `help()` display them.
Example 1 (python)
# Calculate the average
total = 100
count = 4
avg = total / count # inline comment
print(avg)Output
25.0The `#` starts a comment that ends at the newline.
Example 2 (python)
def greet(name):
"""Return a greeting for the given name."""
return f"Hello, {name}"The triple-quoted string is a docstring accessed via `help(greet)`.
Key points
- Use `#` for single-line comments.
- There is no `/* */` in Python.
- Docstrings (triple-quoted strings) document functions and modules.
- Comment WHY, not WHAT โ good code already shows the what.
๐ก Note: Never leave commented-out code in production โ use version control instead.
