Comments in Python
🧠 Here’s a complete cheat sheet on comments, documentation, and code style in Python – ideal for beginners, students, and advanced users. It shows how to use comments correctly, how to document code, and how to write readable, clean Python code.
📝 Python Cheat Sheet – Comments, Documentation & Style #
💬 Comments in Python #
🔹 Single-line Comments #
Use #
to comment a line:
# This is a comment
name = "Lena" # Comment at the end of a line
✅ Ignored by the interpreter
✅ Use them for explanations, notes, or TODOs
🔹 Multi-line Comments (informal) #
Multiple #
lines in a row:
# This is a multi-line comment
# It explains what the following code does
# and why it's important.
🔹 Docstrings (official documentation) #
Use triple quotes """
or '''
for documentation of functions, classes, and modules:
def greeting(name):
"""Returns a greeting for the given name."""
return f"Hello, {name}!"
✅ Docstrings are readable with help()
✅ Used as official description
📚 Docstrings for Classes & Methods #
class Student:
"""Represents a student with name and age."""
def __init__(self, name, age):
"""Initializes the student with name and age."""
self.name = name
self.age = age
🧠 Best Practices for Comments #
✅ Explain the “why”, not just the “what”
✅ Keep comments current – outdated comments are confusing
✅ Avoid obvious comments:
x = x + 1 # Increments x by 1 ❌ (too obvious)
✅ Use comments for complex logic, exceptions, or important notes
🎨 Code Style according to PEP 8 #
Style Rule | Example |
---|---|
Indentation: 4 spaces | def func(): → ␣␣␣␣print() |
Empty line between functions | Separate functions with empty lines |
Max. 79 characters per line | Break long lines |
snake_case for variables |
user_name = "Lena" |
PascalCase for classes |
class Student: |
Spaces around operators | x = a + b |
No spaces before parentheses | print("Hello") |
🧪 TODOs & Notes #
# TODO: Extend function for multiple names
# FIXME: Fix error with number input
# NOTE: This function will be replaced later
✅ Practical for teamwork and personal reminders
🔍 Comments vs. Docstrings #
Type | Purpose | Syntax | Visible with help() |
---|---|---|---|
Comment | Note for developers | # Comment |
❌ No |
Docstring | Documentation for users | """Text""" |
✅ Yes |
🧠 Memory Tip for Students: #
💬 Comments help you think.
📚 Docstrings help others understand.