-3

I'm adding a docstring under my function just to see what's going to happen. When I run it, it returns the docstring instead of my function result. I thought docstring just like the comment that won't affect my result.

enter image description here

Remove the docstring and my function works again. Why is that happening?

enter image description here

Guacaka283
  • 83
  • 6
  • 3
    Welcome to stack overflow, please share your code as text, not as an image https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question – Andrew-Harelson Oct 04 '21 at 00:53
  • 3
    It's only a docstring if it's the very first thing in the function. They don't work anywhere else -- if you want to notate arbitrary positions inside your code, use a comment instead. – Charles Duffy Oct 04 '21 at 00:53
  • 1
    Also, notebook cells aren't functions. – Charles Duffy Oct 04 '21 at 00:57

1 Answers1

0

You should use a normal comment # for this, not a docstring """.

Some tools (like PyCharm or the Sphinx library) docstrings on variables will be respected, but this is not actually built into Python. It is imaginable that in the future Jupyter Notebooks will allow this, but for now they do not, so you should avoid them.

In the official language, docstrings are only used in functions, classes and methods for setting the __doc__ attribute on an object. Regular comments aren't picked up by the interpreter, but strings are. A docstring is just a normal string, but it is parsed differently depending on where it is used. In functions, classes, and methods, they must be the first statement in the block.

For example, in these functions, both foo and bar have proper docstrings, but fizz does not:

def foo():
    "foo"


def bar():
    """bar"""


def fizz():
    # fizz
    pass


print(foo.__doc__)
print(bar.__doc__)
print(fizz.__doc__)
foo
bar
None
flakes
  • 21,558
  • 8
  • 41
  • 88