Using Examples and Code Samples
You'll learn how to write code examples that illuminate concepts and showcase best practices rather than confusing your readers.
Why Examples Matter
Documentation without examples is like a recipe without measurements—technically informative but practically useless. Code samples transform abstract explanations into concrete, actionable guidance. They bridge the gap between "what it does" and "how I use it."
Writing Effective Code Examples
Complete and Runnable
Your examples should work out-of-the-box when possible. Include necessary imports, setup, and context. A half-example forces readers to guess at missing pieces.
Bad:
result = calculate_discount(price, 0.15)
Good:
from pricing import calculate_discount
original_price = 100.00
discount_rate = 0.15
final_price = calculate_discount(original_price, discount_rate)
# Returns: 85.00
Realistic but Simple
Choose scenarios readers will actually encounter, but strip away unnecessary complexity. Your example should feel authentic without overwhelming.
Demonstrate Best Practices
Examples teach by imitation. Show error handling, proper naming, and good patterns—readers will copy what they see.
# Good: Shows validation and clear variable names
def process_user_payment(user_id, amount):
if amount <= 0:
raise ValueError("Payment amount must be positive")
# Process payment logic here
return receipt
Add Explanatory Context
Brief comments or surrounding text should explain why something is done, not just what the code does. Connect the example back to the concept being taught.
Key Takeaway: Effective code examples are complete, realistic, demonstrate best practices, and include just enough context to be immediately useful—they're your documentation's most powerful teaching tool.