CodingNic

Functions and Reusability

Docstrings

Functions and Reusability 18 min read

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:

python
"""
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

python
def greet():
    """Prints a hello message"""
    print("Hello")

greet()

Output

text
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

python
def add(a, b):
    """Returns the total of two numbers"""
    return a + b

print(add(4, 6))

Output

text
10

Reading a Docstring

You can view a docstring with help().

python
def greet():
    """Prints a hello message"""
    print("Hello")

help(greet)

Python shows the saved description.

Good Docstring Example

python
def square(number):
    """
    Returns the square of a number.
    """
    return number * number

Code Along

python
def welcome(name):
    """Prints a welcome message"""
    print("Welcome", name)

welcome("Sara")

Output

text
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 3 and 4

Expected output:

text
12

Real World Use Case

Programs use docstrings in libraries, APIs, tools, and large projects where clear explanations are important.

Quiz

  1. What is a docstring?
  2. What quotes are used for a docstring?
  3. Why are docstrings useful?
  4. 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.