Code

Leave a Note

A docstring is a string written as the very first line of a function's body. It explains what the function does, so future readers (including future you!) don't have to puzzle it out.

def area(width, height):
    """Return the area of a rectangle.

    width and height are lengths in metres.
    """
    return width * height
  • Use triple quotes """ so it can span several lines.
  • The first line is a short summary. Then add details: what the arguments mean and what comes back.
  • Python stores it on the function: help(area) shows it, and so does area.__doc__. Code editors show it when you hover a call.

Pip tip: Comments (#) explain how tricky lines work. Docstrings explain what a function is for.

Assignment

A bridge of length metres needs a lantern at both ends and one every spacing metres in between.

  1. Complete lanterns_needed(length, spacing) so it returns length // spacing + 1.
  2. Give it a docstring (at least a few words) explaining what it returns.