Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! π
Comments & Code Style
Comments explain your code to other developers (and your future self). Python follows PEP 8 - the official style guide. Writing clean, well-commented code is a professional skill.
Comments and Style
- # Single-line comment - ignored by Python
- '''Multiline comment''' or """docstring""" - for longer explanations
- Docstrings ("""...""") - special comments for functions/classes
- PEP 8 - Python's official style guide for clean code
- Use 4 spaces for indentation (not tabs)
- Max line length: 79 characters (or 120 in modern projects)
- Two blank lines before function/class definitions
- Write comments for WHY, not WHAT (code should be self-explanatory)
Comments Code
# This is a single-line comment
print("Hello!") # Inline comment
# Multi-line comments
"""
This is a multi-line comment.
It can span multiple lines.
Often used as docstrings.
"""
# Good vs Bad comments
# BAD: increment counter by 1
count = count + 1 if 'count' in dir() else 1
# GOOD: Retry up to 3 times because API is unreliable
max_retries = 3
# Docstrings (for functions)
def greet(name):
"""Greet a user by name.
Args:
name: The user's name as a string.
Returns:
A greeting string.
"""
return f"Hello, {name}!"
print(greet("Alice"))
print(greet.__doc__) # prints the docstringTip
Tip
Write comments for WHY, not WHAT. The code itself shows WHAT it does. Comments should explain business logic, workarounds, and non-obvious decisions. Use docstrings for functions.
PEP 8 is Python's style guide - follow it and your code looks professional
Common Mistake
Warning
Over-commenting obvious code. # increment x by 1 above x += 1 adds noise. But # Retry because API is unreliable above max_retries = 3 adds value. Comment the intent, not the syntax.
Practice Task
Note
Clean code practice: (1) Write a function with a proper docstring. (2) Add meaningful comments to a 10-line script. (3) Access the docstring with __doc__. (4) Follow PEP 8: 4 spaces, snake_case names.
Quick Quiz
Key Takeaways
- Comments explain your code to other developers (and your future self).
- # Single-line comment - ignored by Python
- '''Multiline comment''' or """docstring""" - for longer explanations
- Docstrings ("""...""") - special comments for functions/classes