← Back to Index

PYTHON COMMENTS

Comments help developers explain code, document decisions, and temporarily disable code without deleting it.

What are Comments in Python?

A comment is text written inside a Python program that Python ignores during execution. Comments are mainly used to explain what the code does, document important decisions, and make programs easier for other developers to understand.

Single-Line Comment

Starts with #. Everything after the # on that line is treated as a comment.

Multi-Line Explanation

Multiple lines can be commented individually using #. This is the preferred approach for normal source-code comments.

Docstrings

Triple-quoted strings can document functions, classes, and modules. These can be accessed using __doc__.

Example 1: User Registration

Comments can explain why specific validation checks are performed when creating a user account.

username = "rahul123"
email = "rahul@example.com"
age = 25

# Check whether the username contains enough characters.
if len(username) >= 5:

    # A valid email should contain the @ symbol.
    if "@" in email:

        # Users must be at least 18 years old.
        if age >= 18:
            print("Registration successful")
        else:
            print("User must be 18 or older")
    else:
        print("Invalid email address")
else:
    print("Username is too short")
Output
Registration successful

Example 2: E-Commerce Order

Comments are useful for explaining business rules in an online shopping application.

product_price = 2500
quantity = 2

# Calculate the total price before applying discounts.
subtotal = product_price * quantity

# Give free shipping when the order exceeds ₹5,000.
if subtotal >= 5000:
    shipping_charge = 0
else:
    shipping_charge = 100

total_amount = subtotal + shipping_charge

print("Subtotal:", subtotal)
print("Shipping:", shipping_charge)
print("Total:", total_amount)
Output
Subtotal: 5000
Shipping: 0
Total: 5000

Example 3: Bank Transaction

Comments can document important financial rules so that future developers understand the reason behind a check.

account_balance = 25000
withdraw_amount = 5000

# The withdrawal should not exceed the available balance.
if withdraw_amount <= account_balance:

    account_balance -= withdraw_amount

    # Record the new balance after the transaction.
    print("Withdrawal successful")
    print("Remaining balance:", account_balance)

else:
    print("Insufficient balance")
Output
Withdrawal successful
Remaining balance: 20000
Real-world note: Financial applications normally use a database, transaction management, authentication, and additional security controls. This example demonstrates only the purpose of comments.

Example 4: Debugging Code

Developers often use comments temporarily while debugging a program to disable a statement or record an observation.

price = 1500
discount = 200

final_price = price - discount

# Debugging:
# print("Price:", price)
# print("Discount:", discount)
# print("Final price:", final_price)

print("Amount to pay:", final_price)
Output
Amount to pay: 1300

Example 5: Login Validation

Comments can describe the purpose of authentication checks without changing the program's behavior.

stored_username = "admin"
stored_password = "Python@123"

entered_username = "admin"
entered_password = "Python@123"

# Compare the username entered by the user.
username_valid = entered_username == stored_username

# Compare the password with the stored credential.
password_valid = entered_password == stored_password

if username_valid and password_valid:
    print("Login successful")
else:
    print("Invalid username or password")
Output
Login successful
Security note: Real applications should never store plain-text passwords. Passwords should be securely hashed and protected.

Example 6: Employee Salary Calculation

Comments can explain the calculation used in business applications such as payroll systems.

basic_salary = 40000
hra = 8000
travel_allowance = 3000

# Gross salary includes basic salary and allowances.
gross_salary = basic_salary + hra + travel_allowance

# Deduct a fixed amount for this simple example.
tax = 5000

net_salary = gross_salary - tax

print("Gross Salary:", gross_salary)
print("Tax:", tax)
print("Net Salary:", net_salary)
Output
Gross Salary: 51000
Tax: 5000
Net Salary: 46000

Example 7: Database Configuration

Comments are commonly used to identify configuration values and explain which environment a setting belongs to.

# Development database configuration
database_host = "localhost"
database_port = 5432

# The application database name used during local development.
database_name = "company_db"

print("Database:", database_name)
print("Host:", database_host)
print("Port:", database_port)
Output
Database: company_db
Host: localhost
Port: 5432

Example 8: Function Documentation

A docstring describes what a function does, its parameters, and what it returns.

def calculate_discount(price, discount_percent):
    """
    Calculate the final price after applying a discount.

    Args:
        price: Original product price.
        discount_percent: Discount percentage.

    Returns:
        Final price after applying the discount.
    """

    discount = price * discount_percent / 100

    return price - discount


final_price = calculate_discount(2000, 10)

print("Final price:", final_price)
Output
Final price: 1800.0
Important: A function docstring is a string object associated with the function and can be accessed using calculate_discount.__doc__.

Comment Types Quick Reference

Type Syntax Purpose Typical Use
Single-line comment # comment Explain one line or small piece of logic Business rules, calculations
Multiple comments # line 1
# line 2
Explain a larger section of code Complex algorithms
Inline comment x = 10 # user age Add a short explanation beside code Constants and variables
Docstring """Documentation""" Document modules, classes and functions Public APIs and reusable code

Comments Best Practices

Write comments that explain why something is done when the reason is not obvious.
Keep comments short, clear, and relevant to the current code.
Update comments when the related code changes.
Avoid comments that simply repeat obvious code.
Use docstrings for functions, classes, and modules that need formal documentation.
Never put passwords, API keys, or sensitive credentials inside comments.

Key Takeaways

Python uses # for normal comments.
Comments are ignored by Python during execution.
Comments make code easier to understand and maintain.
Use comments to explain important decisions and rules.
Use docstrings to document reusable Python code.
Avoid unnecessary or outdated comments.