Docstrings in Python

A docstring (documentation string) in Python is a special kind of comment used to explain what a function, class, or module does. It is written inside """triple quotes""" just below the function definition.

Docstrings are useful for documentation and can be accessed using the .__doc__ attribute.

Syntax:

def function_name(parameters):
    """This is a docstring.
    It explains what the function does."""
    # function body
    ...

Example: Using a docstring in a function

def add(a, b):
    """This function takes two numbers
    and returns their sum."""
    return a + b

print(add(4, 5))
print(add.__doc__)

Output:

9
This function takes two numbers
and returns their sum.

Explanation:

  • add(4, 5) returns 9.
  • When we call add.__doc__, it prints the docstring written inside the function.
  • This is helpful for documentation and to tell other programmers (or yourself) what this function does.

Key Points about Docstrings:

  • Written inside """triple quotes""" immediately after function definition.
  • Can be accessed at runtime using function_name.__doc__.
  • Helps make the code self-documenting and easier to understand.

Summary:

  • Docstrings are used to describe what a function or program does.
  • They do not affect program execution but are very helpful for documentation.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar