Writing Helpful Notes for Humans & Using Function Docstrings
Code is read far more often than it is written. When you write a program today, you might completely forget how it works when you look at it two months from now! Even more importantly, when you work on team projects, other developers need to understand your logic quickly. In Python, we communicate with other humans using comments and docstrings.
A comment is a quick note written directly in your code that Python completely ignores. In Python, any line or part of a line starting with a hash symbol (#) is a comment. Programmers use comments to explain the "why" behind their codeāsuch as why a specific discount rate was applied or what special edge case a line is handling. Good comments explain the reason for the code, not just restating what the code obviously does.
When you write reusable blocks of code called functions, Python provides an official, built-in way to document them called a docstring (short for documentation string). A docstring is written on the very first line inside a function, wrapped in triple quotes: """This function does something useful.""". Unlike regular comments, Python remembers docstrings while your program is running! Anyone can inspect what a function does by checking function.__doc__ or hovering over the function name in their editor.
You will also often see type hints in modern Python, such as def greet(name: str) -> str:. These hints act as helpful road signs: they tell anyone reading the code that greet expects a text string for name, and will return a text string as its result. Together, clean variable names, concise comments, docstrings, and type hints make your code professional, readable, and a joy to maintain.
Real-World Analogy
Comments are like handwritten sticky notes left inside a cookbook explaining why you added a pinch of extra spice, while docstrings are the official recipe title and description printed at the top of the cookbook page explaining what the dish is and how to serve it!
Code ExamplePython 3
# In Python, comments explain WHY code does something.# Single-line comment starts with a hash symbol:
tax_rate = 0.08# State sales tax rate (8%)def calculate_total(subtotal):
"""
Calculate the final invoice total including tax.
Parameters:
subtotal (float): The pre-tax bill amount.
Returns:
float: The final charge with tax added.
"""
returnround(subtotal * (1 + tax_rate), 2)
print("Total:", calculate_total(100.0))
Key Rules & Concepts
Comments begin with # and are completely ignored by Python during execution.
Use comments to explain why a decision was made, not to describe what is already obvious.
Docstrings use triple quotes (""" ... """) on the first line inside a function to document its purpose.
You can inspect any function's docstring using function.__doc__.
Type hints (like user: str -> str) clarify what inputs a function expects and what it returns.
Challenge
Beginner
Write a formatted greeting function equipped with a clean docstring, inspect its docstring metadata, and test user input formatting.
What to do:
Define a function format_greeting(user: str) -> str
Add the docstring: """Format a clean welcome greeting for an authenticated user."""
Inside the function, clean user with user.strip().title(), and return f"Welcome, {clean_user}!"
Print the function docstring with print(format_greeting.__doc__.strip())
Call and print the function with print(format_greeting(" ada lovelace "))
Reference Solution Locked
0 Attempts
Solve the challenge above and run your code to verify it. If you are stuck, you can unlock the reference solution after running your code at least once.
# User greeting function# TODO: Define format_greeting(user: str) -> str:# TODO: Add docstring """Format a clean welcome greeting for an authenticated user."""# TODO: Clean user with .strip().title() and return formatted welcome# TODO: Print format_greeting.__doc__.strip()# TODO: Print format_greeting(" ada lovelace ")
TEST CASESCONSOLE
Output
// Press "Run Code" to execute
Expected Output
Format a clean welcome greeting for an authenticated user.
Welcome, Ada Lovelace!