Loading...

Python Docstrings

A function can carry a sentence that says what it does. That sentence sits in triple quotes, as the first indented line under def. It is stored on the function. It is not the text the function hands back when you call it. hello takes one name. The stored sentence says that the function returns hello plus that name. The return line builds the word hello, a space, and the name. You do not install a package and you do not create a folder. The first print writes the stored sentence. The second print writes the hello for lena. Nothing on this page stops.

a description stored on hello

python
def hello(name):
    """Return hello plus the name."""
    return "hello " + name

print(hello.__doc__)
print(hello("lena"))

The screen shows two lines. The first is Return hello plus the name. The period is part of that sentence. There are no quote marks around it, and there is no decimal point. The second line is hello lena. lena is the name passed into hello. The space between hello and lena sits in the return line, before the name is joined on. Those two lines are different pieces of text. The first is the description you stored. The second is what the call hands back. print writes each of them, and then the program finishes. None is not written. Reading those two lines is enough. You do not need a second tool.

A line that starts with # is a note for someone reading the file. It is not stored on hello. If the triple-quoted line is left out, the description is missing, and the first print writes None. The call still writes hello lena, and the program still finishes. That missing line is not in this program. The triple quotes have to be the first indented line under def. A string written later, after another line, does not become the description. This page does not build a class. It does not put one object inside another, and it does not look for a wrong seat count.

📊 Two lines on the screen

What you print What that line shows
the description stored on hello Return hello plus the name.
hello("lena") hello lena

The next page is choosing names. This page only stores a one-line description on hello, then prints that description and the returned hello.

The description is not the hello

The first line of the screen is Return hello plus the name. The second line is hello lena. A hash note is not stored. Leave the triple quotes out and the description is None. The next page is choosing names.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
6
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top