Documenting Functions

CS 65: Introduction to Computer Science I

The help() function

Python provides a built-in help() function that shows you how to use other functions. You can check it out in the interactive shell in Thonny like this:

Go ahead and try it yourself on other functions we've used.

To use it with a method, you need to use dot notation with an appropriate object, but as above, just use the name and not parentheses.

In [4]:
help([].index)
Help on built-in function index:

index(value, start=0, stop=9223372036854775807, /) method of builtins.list instance
    Return first index of value.
    
    Raises ValueError if the value is not present.

Docstrings

You can (and should!) support this with your functions too.

To do it, add a docstring, a multiline comment starting as the first line in your function.

Things typically included:

  • a description of the function's purpose
  • a description of each parameter - so that they know what to pass as arguments
  • a description of the return value, if any - so they know how to use what they get back
In [5]:
def f_to_c(fahrenheit_temp):
    """
    Convert a temperature from Fahrenheit to its Celsius equivalent.
    
    Paremeters:
        fahrenheit_temp: a float, the Fahrenheit temperature to be converted
        
    Returns:
        a float, the temperature converted into Celsius
    """
    celsius_temp = (fahrenheit_temp-32)*(5/9)
    return celsius_temp
In [6]:
help(f_to_c)
Help on function f_to_c in module __main__:

f_to_c(fahrenheit_temp)
    Convert a temperature from Fahrenheit to its Celsius equivalent.
    
    Paremeters:
        fahrenheit_temp: a float, the Fahrenheit temperature to be converted
        
    Returns:
        a float, the temperature converted into Celsius