A function in Python represents lines of code or a block of code that do a specific task. These lines of code are often given a descriptive name that you an idea of what the function does. Functions allow for code reuse, sharing, and also make code easier to maintain. Bigger or longer lines of code can be broken down into smaller chunks by leveraging functions. This is particularly useful in cases where the same lines of code, that perform a given task, are needed in several places within an application. Furthermore, the use of functions helps reduce the number of lines of code. In addition, if there are any errors associated with those lines of code, the changes/fix will only be needed to be made in one location (within the function).
There are many functions out there for most of the common tasks such as sorting values and calculating the lengths of objects. Indeed, one can leverage these functions and avoid having to ‘re-invent the wheel’. An example would be the in-built function ‘len’ that returns the length of an object and the function ‘type’ that returns the type of an object.
Creating and accessing a function
A function is created using Python’s keyword ‘def’ (short form for definition). The ‘def’ keyword is typed followed by a blank space, followed by the name of the function, followed by opening and closing parentheses. Finally, the line ends will a colon. All the code associated with the function is indented under the function’s definition line.
Example:
def my_function():
print('This is a test function')
Running the above code will not generate any output. The task that is performed by a function can be accessed by ‘calling’ the function in question. The approach of calling a function is similar to using built-in functions such as len and print. To call the function, type the name of the function followed by parentheses.
Example:
my_function() # This calls the function which in turn executes code that is indented under the def line.
Use of comments in a function
While comments are optional, it is best practice to include a docstring (a statement enclosed in triple quotation marks) as the first line under the def statement line. The docstring is used to give a brief description of what the function does. A comment, that is preceded by the # sign, can also be added after the parentheses in the definition line. Comments are just notes for reference and do not have any effect on the code’s functionality (i.e., comments are not executed by the interpreter).
Example:
def my_function(): # Test function
'''A docstring providing a brief description of what the function does'''
print('This is a test function')
Passing arguments/information to a function
Information can be passed to a function in the form of parameters. A parameter name is input inside the parentheses of the function’s definition line. The parameter name has to follow similar rules as variables in that it can start with an underscore or a letter, followed by a number, a letter, or an underscore. For code readability, it is recommended that the parameter name describes what item is being passed. For example, rather than using the variable ‘x’ to represent the first name or a person, one should use the variable ‘first_name’. It is important to note that a parameter is local to the function and hence has no effect on a variable with a similar name and that is located outside the function. This is also referred to as local scope, which means that a variable created and modified inside a function stops existing once the function stops running. However, a new value may be returned by the function and this new value will be available outside the function.
Example:
def hello(first_name): # Test function
'''type docstring here'''
print('Hello ' + first_name)
Example of calling the function and passing and argument:
hello(‘Inno Techtips’)
The resulting output will be: Hello Inno TechTips
If the function is called without passing the argument, an error will be generated. The value passed in can be the actual data item or a variable that points to the value.
Example:
my_name = 'Inno TechTips' # Store the name string inside a variable
hello(my_name) # Call the function using the variable that contains the value of the name
Using defaults to define optional parameters
If the function is called without passing the argument, an error will be generated. The error would state that a required positional argument is missing for the called function. This error can be avoided by specifying a default value that would be used in case an argument is not passed. This is done by assigning a value to the parameter inside the parentheses. In this case, passing an argument is optional when the function is called.
Example:
def hello(first_name = 'Somebody'): # Test function
'''type docstring here'''
print('Hello ' + first_name)
hello() # Calling the function without inputting an argument will give the following output:
Hello Somebody
Inputting multiple parameters in a function
When it comes to passing arguments to a function, the function can be created such that it allows for the input of multiple arguments. For instance, a function can be created with two parameters: first and last name.
Example:
def hello(first_name, last_name ): # Test function
'''This function accepts takes two arguments'''
print('Hello and welcome, ' + first_name + ' ' + last_name)
The function can then be called/executed using the following example:
hello('Inno', 'Techtips') The resulting in the following output: Hello and welcome, Inno Techtips
NOTE: When mixing optional parameters (those defined with default values) with required parameters, the non-optional parameters have to be listed first within the parentheses. Otherwise, a syntax error message (e.g., the non-default argument follows default argument) will be generated when attempting to run the code.
Keyword arguments (or Kwargs)
Use of keyword arguments is yet another way to pass arguments to functions in Python. The word ‘argument’ is the Python term that describes the value that is passed to a function when it is called. You can think of the arguments as being passed to the parameters defined by the function. There are two types of arguments: positional and keyword arguments. The positional arguments are passed based on the position.
Example:
hello(‘Inno’, ‘Techtips’) # Here the interpreter assumes ‘Inno’ is the first name
The use of keyword arguments allows the parameter names to be assigned argument values when the function is being executed or called.
Example:
hello(last_name = ‘Techtips’, first_name = ‘Inno’) # Here parameter name last_name is assigned the argument value Techtips when calling the function. Notice that the order here does not matter.
Passing an unspecified number of arguments
Some functions may be defined such that they can accept a variable number of arguments. Use the*args or *vars (here, what matters is the asterisk) convention to define a function that takes any number of arguments. The arguments that are passed to this function become a tuple. The tuple can be worked with directly or it can be converted to a different data structure such as a list.
Example:
def test_variable_args(*args):
for arg in args:
print("Variable is:", arg)
test_variable_args(1, 3, 8, 'test') # call the function
Resulting output:
Variable is: 1
Variable is: 3
Variable is: 8
Variable is: test
Functions that return values
In some cases, you may want your function to return a value. Often times the returned value is assigned a variable by the calling code. In most cases, the line that performs the return action is the last line within the function. The line will start with the keyword ‘return’ followed by that which is to be returned, which could be a variable or expression.
Example:
def my_multiplier(a, b):
""" Function returns the product of two numbers. """
product = a * b # Multiple the two provided arguments and assign to a variable named product
return product # Return the product/result of the multiplication
result = my_multiplier(2, 3) # Call the function and assign the return value to a variable
print ('The value returned by the function is:', result) # Print the value of the variable
Resulting output:
The value returned by the function is: 6