Description
A function is a mechanism for encapsulating a block of code. You can repeat the behavior of this block in multiple spots without having to duplicate the code. Your code will be better organized, more testable, maintainable, and easier to understand.
Anatomy of a Function
Defining a Function
The first line of a function definition starts with the keyword def, followed by the function name, function parameters enclosed in parentheses, and then :. The rest of the function is a code block and is indented:
1 | def <FUNCTION NAME>(<PARAMETERS>): |
If a string using multiline syntax is provided first in the indented block, it acts as documentation. Use these to describe what your function does, how parameters work, and what it can be expected to return. You will find these docstrings are invaluable for communicating with future users of your code. Various programs and services also use them to create documentation. Providing docstrings is considered a best practice and is highly recommended:
Function arguments occur in the parentheses following the function name. They can be either positional or keyword. Positional arguments use the order of the arguments to assign value:
With keyword arguments, assign each argument a default value:
The default values are used when no values are passed during function invocation. The keyword parameters can be called by name during function invocation, in which case the order will not matter.
1 | # This is a sample Python script with two variables and one function |
Call / Execute Your Function
A function is a Block of code that only runs when it is called.
Calling a function = executing the function.
1 | def days_to_units(): |
Add Parameters to your function
Information can bee passed into functions as parameters.
Parameters are also called arguments.
1 | # This is a sample Python script |
Passing Multiple Parameters to a Function
1 | # This is a sample Python script |
Adding Comments to your functions
Comments should have a maximum length of 72 characters. They should describe what the function does, what parameters work, and what the function returns.
1 | # This is a sample Python script |
Functions as Objects
Functions are objects. They can be passed around, or stored in data structures. You can define two functions, put them in a list, and then iterate through the list to invoke them.