📝 What are Comments in Python?
Comments are explanatory notes written inside source code for humans to read. Python interpreter completely ignores comments during execution. They are critical for maintaining clean code, documenting functions, explaining algorithms, and collaborating with team members across software projects.
1. Single-Line Comments (#)
Single-line comments start with the hash symbol (
#). Everything following it on that line is ignored by Python.
Python
# This is a single-line comment
print("Hello, World!") # This is an inline comment explaining the print statement
Output:
Hello, World!
Real-Time Example 1: Explaining Mathematical Business Logic
Use comments to document formulas, tax computations, or business rules so other developers understand the math.
Python
# Compute item price after applying a 18% GST tax and 10% discount
base_price = 2500
discount_rate = 0.10 # 10% promotional discount
gst_rate = 0.18 # 18% standard goods & services tax
final_price = (base_price - (base_price * discount_rate)) * (1 + gst_rate)
print("Calculated Final Retail Price: ₹", final_price)
Output:
Calculated Final Retail Price: ₹ 2655.0
Real-Time Example 2: Multi-Line Comments & Docstrings
Python does not have a dedicated multi-line comment symbol, but triple quotes (
""" or ''') are used as docstrings to document functions and modules.
Python
def calculate_rectangle_area(length, width):
"""
Function: calculate_rectangle_area
Purpose: Computes the total area of a rectangle.
Parameters: length (float), width (float)
Returns: area (float)
"""
return length * width
print("Area:", calculate_rectangle_area(12.5, 4.0))
Output:
Area: 50.0
Real-Time Example 3: Disabling Code During Testing / Debugging
Temporarily comment out lines of code to isolate bugs or skip test blocks without deleting them.
Python
print("Step 1: Initializing connection...")
# print("Step 2: Authenticating admin credentials...") # Temporarily skipped for debugging
print("Step 3: Loading dashboard modules...")
Output:
Step 1: Initializing connection...
Step 3: Loading dashboard modules...
Real-Time Example 4: TODO and FIXME Task Tracking
Professional developers use standardized keywords like
TODO or FIXME in comments to highlight future improvements or bug fixes.
Python
def connect_database():
# TODO: Implement secure environment variable lookup for password
# FIXME: Add auto-reconnect logic if connection drops
return "Database connection established."
print(connect_database())
Output:
Database connection established.
Real-Time Example 5: Section Dividers in Large Code Files
Use decorative comment blocks to organize long Python scripts into clear logical sections.
Python
# ==========================================
# CONFIGURATION CONSTANTS
# ==========================================
API_TIMEOUT_SECONDS = 30
MAX_LOGIN_RETRIES = 3
print(f"Loaded config: Timeout = {API_TIMEOUT_SECONDS}s")
Output:
Loaded config: Timeout = 30s
Real-Time Example 6: Explaining Regular Expressions (Regex)
Complex regular expressions can be hard to read; comments break down what each pattern segment matches.
Python
# Email validation pattern explanation:
# ^[a-zA-Z0-9_.+-]+ -> matches local username part
# @ -> matches mandatory @ symbol
# [a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$ -> matches domain and extension
email_regex_example = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
print("Regex pattern documented successfully.")
Output:
Regex pattern documented successfully.
Real-Time Example 7: Documenting API Endpoints
Document expected JSON request and response payloads directly above controller functions.
Python
def api_user_login(payload):
"""
Endpoint: POST /api/v1/login
Request JSON: {"username": str, "token": str}
Response JSON: {"status": "success", "code": 200}
"""
return {"status": "success", "code": 200}
print(api_user_login({"username": "nikita"}))
Output:
{'status': 'success', 'code': 200}
Real-Time Example 8: Warning Notes for Edge Cases
Leave cautionary comments for future maintainers about potential performance bottlenecks or data pitfalls.
Python
def process_large_dataset(records):
# WARNING: Do not pass lists exceeding 100,000 items without batching,
# otherwise memory consumption will spike and trigger an Out-Of-Memory error.
return f"Processed {len(records)} records safely."
print(process_large_dataset([1, 2, 3, 4, 5]))
Output:
Processed 5 records safely.
Real-Time Example 9: Type Hint and Algorithm References
Reference external specifications, RFC standards, or mathematical papers in algorithm comments.
Python
# Algorithm adapted from standard Base64 RFC 4648 specifications
def encode_identifier(identifier_str):
# Reference: https://datatracker.ietf.org/doc/html/rfc4648
return f"Encoded::{identifier_str}"
print(encode_identifier("NikitaInfotech"))
Output:
Encoded::NikitaInfotech