Labs ICT
โญ Pro Login

Comments

2 min read | Python Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Single-Line Comments

The # character tells Python to ignore everything after it on that line. Use it to explain what your code does.

# Display a welcome message
print("Welcome to Python!")

End-of-Line Comments

You can also place comments at the end of a line of code. Just make sure the code comes first.

x = 42  # The answer to everything

Commenting Variables

Use comments to describe what a variable represents when the name alone isn't enough.

pi = 3.14159  # Approximate value of pi
radius = 5  # Circle radius in meters

Disabling Code

Comments are great for temporarily disabling code during debugging. Just add a # at the start of the line.

# print("This won't run")
print("This will run")

Multi-Line Comments

Python doesn't have a dedicated multi-line comment syntax. Instead, you can use multiple # lines or a multi-line string that isn't assigned to anything.

"""
This is a multi-line string
used as a comment.
It can span several lines.
"""
print("Still works!")

Docstrings

Docstrings are multi-line strings that document functions, classes, and modules. They're technically not comments, but they serve the same purpose.

def greet(name):
    """Say hello to someone."""
    print(f"Hello, {name}!")

greet("Alice")

Good Comments vs Bad Comments

Good comments explain why, not what. The code already says what it does. Use comments to explain decisions, calculations, or tricky parts.

# Bad comment - explains the obvious
x = x + 1  # Add one to x

# Good comment - explains the reasoning
x = x + 1  # Offset for zero-based index

Inline Comments

Avoid long inline comments that break the flow. If you need more than a few words, put the comment on its own line above the code.

# Calculate total price with 8% sales tax
total = price * 1.08

Commenting Out During Debugging

When you're testing different approaches, comment out the old code rather than deleting it. Once you're sure the new code works, clean up the comments.

# print("Version 1")
print("Version 2 - improved")

๐Ÿงช Quick Quiz

How do you write a single-line comment in Python?