In this lesson, we explore comments and how to create documentation for Python programs. Comments help explain code, while documentation provides detailed instructions for users and developers.
A comment is a part of the code that the interpreter ignores. It is used to explain code or temporarily disable certain lines during testing.
Use #
to create single-line comments:
# This is a single-line comment
print("Hello, World!")
Output:
Hello, World!
print("Hello, World!") # Printing Hello, World
Output:
Hello, World!
print("Python Program")
# print("This line is disabled")
Output:
Python Program
To create multi-line comments, use #
at the start of each line or use multi-line strings.
#
for Multi-Line Comments# This is a multi-line comment
# explaining a block of code.
x = 10
y = 20
print(x + y)
Output:
30
Multi-line strings enclosed in triple quotes can also serve as comments:
"""This is a multi-line comment
explaining a block of code."""
x = 10
y = 20
print(x + y)
Output:
30
Python provides ways to add documentation to your programs, making them easier to understand and use.
Docstrings are special strings used to document a Python module, class, function, or method. They are enclosed in triple quotes ("""
or '''
) and appear as the first statement inside the respective block.
def greet(name):
"""This function greets a person with the given name."""
return f"Hello, {name}!"
print(greet("Alice"))
Output:
Hello, Alice!
You can access a function's docstring using the __doc__
attribute:
print(greet.__doc__)
Output:
This function greets a person with the given name.
class Calculator:
"""This class performs basic mathematical operations."""
def add(self, a, b):
"""Returns the sum of a and b."""
return a + b
calc = Calculator()
print(calc.add(5, 3))
print(Calculator.__doc__)
Output:
8
This class performs basic mathematical operations.
Add a docstring at the beginning of a Python file to describe the module:
"""This module provides utility functions for string manipulation."""
def reverse_string(s):
return s[::-1]
Objective: Create a Python script with well-structured comments and documentation.
Create a Script: Write a Python program to calculate the factorial of a number.
Add Comments: Use single-line and multi-line comments to explain each step.
Document the Program:
Example:
"""This script calculates the factorial of a given number."""
def factorial(n):
"""Calculates the factorial of n using recursion."""
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
# Input from the user
num = int(input("Enter a number: "))
# Calculating the factorial
result = factorial(num)
# Printing the result
print(f"The factorial of {num} is {result}.")
With these tools, you can write Python programs that are not only functional but also easy to understand and maintain. Let’s move to the next topic!