Python Comments
- Used to explain what the code does.
- Written with a
#
and ignored by the Python interpreter. - Meant for developers and do not appear in the output.
Example:
# Takes in a number n, returns the square of n
def square(n):
return n**2
Use comments to clarify logic, TODOs, or complex decisions that aren’t obvious from the code alone.
Python Docstrings
- Used to explain what the code or a function is intended for.
- Written as a string literal after a function, class, or module definition.
- Can be accessed at runtime using the
__doc__
attribute. - Used by documentation tools and IDEs for generating reference docs or tooltips.
Example:
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2
print(square.__doc__)
Output:
Takes in a number n, returns the square of n
Tip:
Use comments to explain the "how" and docstrings to explain the "what and why" of code functionality.
👉 Next tutorial: Python PEP 8