Functions and Docstring
Functions
Functions allows you to create a sequence of code that can be called repeatedly so you don’t need to write everything out multiple times.
To create a function, you use def
followed by your name for the function followed by ():
. Then on the next line you’ll start your code. If you want you function to give a result at the end, you’ll use return
and then the result you want to return.
To use a function you’ve created, it’s the same as using print()
, input()
, range()
etc.
You can also give a function something called parameters. These are variables that can be used inside the function itself. This allows you to create a general function that can give different results based on what you input. These are put inside the ()
in your method definition.
You can give parameters a default value. This enables the parameter to be used in your function without explicitly needing to give the function a value for that parameter when you call it. To do this, you add =value
after a parameter, where value
will be what you want to set as the default. You can override this default when calling the function and replace it with a given value.
Docstrings
Docstrings are used to document a function, its parameters, what it does, and its output. These are block comments put at the start of a function, surrounded by """
. Visual Studio (and VS Code) use something called Intellisense, which is a code-completion tool. One of the things this does is it will show you what your docstrings look like when rendered properly.
The render for this docstring using intellisense looks like this:
The docstring style above is a common one called Google Docstring Style. It’s an easy docstring format to remember and is quite clear. There are other styles you can use, however.