A function is a code block that contains several lines of reusable code which perform a specific task or job. To execute a task, you only need to call the function responsible for it.
In this article, you will understand what python functions are; types of functions in python; how to define functions in python.
Why are Python Functions Necessary?
Functions make your program clean, organized, easy to read and easy to maintain. It also reduces redundancy in your program.
You only need to define a function once. After which the function can be called severally from anywhere in the program.
These functions can also be used in another program by importing them.
Types of Functions in Python
Built-in functions
These are predefined functions in python. They can be called from anywhere in a python program without importing them.
print, len, sum, min, max are examples of predefined python functions:
User-defined functions
These are functions created by you as a programmer. They are defined by you before being called later in your program.
How to Define a Function
The first line in a function definition is the def keyword followed by the function name, a parenthesis, which can include optional parameters, and a colon.
The subsequent line(s) must be indented. These indented lines of code make up the body of the function.
It is a good practice to include a comment (docstring) in your function definition. This should explain what and how a function works to users of your program.
def message(): """Greet the user""" print('Hello there')
The above code is a simple function that prints a message.
Your function name must follow the guidelines for choosing variable names.
Each function must also have a unique name. Defining a function with a pre-existing function name overwrites the previous function definition.
How to call a function
To call a function, the function name is followed by a parenthesis supplied with arguments, if any.
Let’s call our previously defined function
This simple function does not require an argument as this was not specified in the function definition.
Parameters and Arguments in Functions
Parameters and arguments are often misconstrued. These terms have different meanings.
Parameters are information supplied to a function during its definition while arguments are supplied during a function call.
Let’s modify our previously defined function to take a parameter, name. This parameter can be used only within the function.
def message(name): """Greet the user""" print(f'Hello {name.title()}')
Let’s call it by supplying an argument.
The number of arguments supplied during a function call must match the number of parameters supplied during the function definition. Supplying more or less required arguments to a function would throw an error.
Let’s create a function to compare the mean of two lists of numbers.
def compare(first_list,second_list): """Compare the mean of two lists""" first_sum = sum(first_list) first_length = len(first_list) first_mean = first_sum/first_length second_sum = sum(second_list) second_length = len(second_list) second_mean = second_sum/second_length print((first_mean, second_mean)) compare([1,2,3],[2,4,6])
The only arguments needed for this function are the lists. It computes the total and divides it by the number of elements in the list. The last line in the function prints the results of both lists in a tuple.
Return Statements in Python
So far, we’ve only printed results. return statements make it easy for us to reuse results from functions. The return statement passes the result to the caller of the function. This way, the result can be stored in a variable as shown below.
def compare(first_list,second_list): """Compare the mean of two lists""" first_sum = sum(first_list) first_length = len(first_list) first_mean = first_sum/first_length second_sum = sum(second_list) second_length = len(second_list) second_mean = second_sum/second_length return(first_mean, second_mean) first, second = compare([1,2,3],[2,4,6])
To print the result, we can either print it directly or store it in a variable before printing.
Positional Arguments
The order in which you supply arguments to a function matters. Consider a function that prints your information. If the function definition specifies that your name should be supplied before your age, reversing the position would have a different meaning.
def info(name,age): """Print user info""" print(f'My name is {name}') print(f'I am {age} years old') print('correct order') info('Laycon',26) print('') print('wrong order') info(26,'Laycon')
Keyword Arguments
You can explicitly supply values to a function. By this way, order doesn’t matter. Just ensure to use the exact parameter used in the function definition.
The previous code can be written as
Optional Arguments
You can make an argument optional by specifying a default value. This implies that the function will run even when a user does not supply the argument. Python will resort to using the default value specified in the function definition.
def info(name,age,form='robot'): """Print user info""" print(f'My name is {name}') print(f'I am {age} years old') print(f'I am a {form}')
We supplied a default value for form. Let’s call the function with and without the form argument.
Summary
- A function is a code block that contains several lines of reusable code which perform a specific task or job
- There are two types of functions namely: built-in and user-defined functions
- To define a function in python, the def keyword is followed by the function name, a parenthesis which nests parameter(s), a colon and an indented code block
No comments: