A docstring is a special string placed in a Python function to document its purpose and behavior. Unlike a quick comment, it can become part of the function’s documentation. section 14.0
Think of it as leaving a helpful note for your future self—or for someone else reading your code months later. Keep explaining original or complicated code yourself, even when AI can suggest comments. section 14.0
Documenting a menu reader
The function’s docstring states what read_menu does, names its filename parameter, describes the returned list, and notes that surrounding whitespace is removed. section 14.0
def read_menu(filename):
"""
Reads the menu from a file and returns a list of items.
:param filename: The name of the file containing the menu.
:return: A list of menu items, with leading and trailing
whitespaces removed.
"""
try:
# Open the file using 'with' to ensure it's properly
# closed after use
with open(filename) as f:
# Read all lines from the file and remove whitespaces
# using list comprehension
result = [item.strip() for item in f.readlines()]
except FileNotFoundError:
# Handle the case when the file does not exist
print(f"Error: The file '{filename}' could not be found.")
result = []
except PermissionError:
# Handle the case when there is no permission to read
# the file
print(f"Error: You do not have permission to read \
the file '{filename}'.")
result = []
except Exception as e:
# Handle any other unexpected errors
print(f"An unexpected error occurred: {e}")
result = []
return result
Inspect a complete docstring alongside comments explaining file handling and exception cases. section 14.0





