Skip to Content

What Is the Purpose of a Docstring in a Python Function?

Why Should You Use Docstrings in Python Functions for Cleaner Code?

Learn the primary purpose of a docstring in a Python function, including how it documents behavior, parameters, and return values to improve readability and code maintenance.

Question

What is the primary purpose of a docstring in a Python function?

A. To execute additional lines of code when the function runs
B. To import external modules into the function
C. To describe what the function does, its parameters, and return values
D. To define variable types within a function

Answer

C. To describe what the function does, its parameters, and return values

Explanation

The primary purpose of a docstring in a Python function is to describe what the function does, the parameters it accepts, and the value it returns. It serves as built-in documentation, making the code easier to understand, maintain, and use correctly.