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 function 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.
Type Hints
Variables in Python are dynamically typed. They can change depending on what values you give them. This can be a bit confusing. You can give variables type hints to help Python know what you’re intending. It also helps with readability and error detection. The syntax for it requires adding : type
after your variable name. To do type hinting with more complex structures such as lists, you must also provide what type will be in the list using the syntax [type]
.
This can also be used within functions and parameters. The syntax for parameters is the same, but you can also use it to hint at what type you want to return using -> type
There is an external package called mypy which will check the static (type hinted) code in your program and tell you if you’re using variables of the wrong types, according to your provided type hints. Mypy will be expanded on further in the Setting Up section.
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.