๐ ๐๏ธ Python Commenting and Docstrings#
๐ What are Comments?#
Comments in Python are lines in the code that are not executed. They are meant for:
Explaining the purpose of the code
Making the code easier to read
Debugging purposes during development
Types of Comments:#
Single-line comments: Start with
#
.Multi-line comments: Use triple quotes (
'''
or"""
).
# Single-line comment example
x = 10 # This is an inline comment explaining the variable
# Multi-line comment example
"""
This is a multi-line comment.
It spans multiple lines to explain the code below.
"""
y = 20
z = x + y
๐ What are Docstrings?#
Docstrings are special strings used to document a Python module, class, or function.
They describe what the code does, parameters, and return values.
Docstrings are defined using triple quotes (
'''
or"""
).
Example of a Docstring in a Function:#
def add_numbers(a, b):
"""
Add two numbers and return the result.
Parameters:
a (int): First number
b (int): Second number
Returns:
int: The sum of a and b
"""
return a + b
๐ Accessing Docstrings in Jupyter Notebook#
You can view the docstring of a function, class, or module using:
The
help()
function.The
.__doc__
attribute.
Examples:#
# Accessing docstring using help()
help(add_numbers)
# Accessing docstring using __doc__
print(add_numbers.__doc__)
Help on function add_numbers in module __main__:
add_numbers(a, b)
Add two numbers and return the result.
Parameters:
a (int): First number
b (int): Second number
Returns:
int: The sum of a and b
Add two numbers and return the result.
Parameters:
a (int): First number
b (int): Second number
Returns:
int: The sum of a and b