Python comments
Table of Contents
Description
Comments in Python are lines in the code that are not executed by the interpreter. They are used to explain code, make it more readable, and leave notes for other developers (or your future self).
Python supports:
Single-line comments using the # symbol.
Multi-line comments using triple quotes (''' or """) — though these are technically multi-line strings, they’re often used as block comments or docstrings.
Prerequisites
- Basic knowledge of writing and running Python code.
- Understanding of syntax and code structure.
Examples
Here's a simple program in Python:
# This is a single-line comment print("Hello, world!") # This comment follows code on the same line # Below is a function that adds two numbers def add(a, b): return a + b # Returns the sum ''' This is a multi-line comment. Technically, it's a multi-line string not assigned to any variable. Often used to describe blocks of code. ''' # Example with docstring def greet(name): """ This function greets the person passed as an argument. """ print(f"Hello, {name}!")Real-World Applications
Writing documentation inside code for teams or open-source projects.
Explaining logic for complex or non-obvious code.
Temporarily disabling code during debugging or testing.
Adding TODOs or FIXMEs as reminders for future improvements.
Where topic Can Be Applied
All Python programs: Used for documenting functions, classes, or modules.
Collaborative development: Teams use comments to make code understandable.
Open-source projects: Comments help others understand the codebase.
Educational material: Instructors use comments to explain logic in tutorials.
Debugging and testing: Developers comment out sections for temporary changes.
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
What are comments in Python and why are they important?
How do you write a single-line and multi-line comment in Python?
What is the difference between a comment and a docstring?
Can multi-line strings be used as comments? Is it recommended?
How can comments improve code quality and maintainability?