Comments in Python
Comments are notes written inside the code to explain what the code does. They help programmers understand the code later or help others reading it. Comments are ignored by the Python interpreter and have no effect on the program execution.
Types of Comments
1. Single-line Comments
- Start with the hash symbol
#
. - Everything after
#
on the same line is considered a comment.
Example:
# This is a single-line comment
print("Hello, world!") # This prints a greeting message
Output:
Hello, world!
2. Multi-line Comments
Python does not have a special multi-line comment syntax like some other languages, but you can use multiple single-line comments:
# This is a multi-line comment
# written using multiple
# single-line comment symbols
Or you can use triple-quoted strings (''' ... '''
or """ ... """
) to write multi-line comments. While these are actually multi-line strings, if they are not assigned to a variable or used in expressions, they behave like comments.
"""
This is a multi-line comment.
It can span multiple lines.
Usually used for docstrings.
"""
print("Hello")
This also runs the program normally and ignores the multi-line string.
Docstrings — Special Multi-line Comments
Docstrings are special multi-line comments used to document functions, classes, or modules. They are enclosed in triple quotes and are accessible through Python's help system.
Example:
def greet(name):
"""
This function greets the person passed in as a parameter.
"""
print(f"Hello, {name}!")
greet("Alice")
You can access the docstring like this:
print(greet.__doc__)
Output:
This function greets the person passed in as a parameter.
Summary
Comment Type | Syntax | Usage |
---|---|---|
Single-line comment | # comment |
For short notes |
Multi-line comment | Multiple # lines |
For longer explanations |
Multi-line string | ''' ... ''' or """ ... """ |
Often for docstrings or large comments |
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.