Python Functions Tutorial: def, return, Arguments and lambda with Examples
P7.6 How to Write a Docstring for a Python Function
In short: A docstring is a text in triple quotes as the first line of the function. help(func) shows it.
Why. A teammate (or you, later) needs to know what the function expects and returns without reading every line.
What. A docstring is a text in triple quotes as the first line of the function. help(func) shows it.
How.
Document a function
- Right after the
defline, open""". - Write one line: what it does.
- Mention inputs and the return value.
- Close with
""".
Worked example A — A documented cleaner.
Step 1 — What we do. A function used by a healthcare data team.
Step 2 — Type and run this code.
def clean_name(text):
"""Return a patient name with no outer spaces and Title Case."""
return text.strip().title()
print(clean_name(" maria lopez "))
print(clean_name.__doc__)
Step 3 — Output you should see.
Maria Lopez
Return a patient name with no outer spaces and Title Case.
Step 4 — What it means. The docstring is stored with the function. In Jupyter, press Shift+Tab inside the brackets to see it.
Ravindra Bagale's Tip
One clear sentence in a docstring is better than none. Write it while the idea is fresh.
Ravindra Bagale's Tip – मराठी
Docstring मध्ये एक स्पष्ट वाक्य काहीच नसण्यापेक्षा चांगलं. कल्पना ताजी असतानाच लिहा.
Ravindra Bagale's Tip – हिंदी
Docstring में एक साफ़ वाक्य कुछ न होने से बेहतर. Idea ताज़ा हो तभी लिख दो.
Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.