Docstrings
Docstrings
As programs grow, it becomes important to explain what functions do.
Python gives us a clean way to write notes inside functions.
These notes are called docstrings.
What Is a Docstring?
A docstring is a description written inside a function.
It explains what the function does.
A docstring is written using triple quotes:
"""
Text goes here
"""
Why Docstrings Matter
Docstrings help you:
- Understand code later
- Help other developers
- Explain inputs and outputs
- Make code easier to maintain
Simple Example
def greet():
"""Prints a hello message"""
print("Hello")
greet()
Output
Hello
How This Works
Let’s break it down:
def greet():creates the function- The text inside triple quotes is the docstring
- Python stores that description
- The function still runs normally
Another Example
def add(a, b):
"""Returns the total of two numbers"""
return a + b
print(add(4, 6))
Output
10
Reading a Docstring
You can view a docstring with help().
def greet():
"""Prints a hello message"""
print("Hello")
help(greet)
Python shows the saved description.
Good Docstring Example
def square(number):
"""
Returns the square of a number.
"""
return number * number
Code Along
def welcome(name):
"""Prints a welcome message"""
print("Welcome", name)
welcome("Sara")
Output
Welcome Sara
Mini Challenge
Build a math function with a docstring.
Steps:
- Create a function called
multiply - Add two parameters
- Write a docstring explaining the function
- Return the answer
- Print the result of
3and4
Expected output:
12
Real World Use Case
Programs use docstrings in libraries, APIs, tools, and large projects where clear explanations are important.
Quiz
- What is a docstring?
- What quotes are used for a docstring?
- Why are docstrings useful?
- Which function can display a docstring?
Assignment
Create a function called divide with a docstring. Return the result of two numbers and print the answer.
Summary
You learned that docstrings are built-in notes for functions that explain what code does and make programs easier to understand.