Let us start with a real-life example,
Imagine you are building a fence. You need to know how much wood is needed to build it. Now you can not just sit and calculate the area and use math. Instead, you can use functions that take the width and height as inputs and calculate the total area. This avoids errors and saves you time.
In my own words, a function is a reusable block of code that performs a specific task or set of tasks that only returns when it is called. If there is a certain code that has to be written again and again for different inputs, we make use of functions.
SYNTAX:
We use def keyword to define the function, followed by the function name. In parenthesis, we pass the parameters/arguments. The function block starts with a colon " : " and there should be an indentation while writing the block statements. We use return statement to return the function value. There should be only one return statement in the function.
There are two types of functions:
1. Built-in functions
These functions are already precoded in Python, we can directly use those functions.
Eg: print(), len(), max(), type(), etc.
2. User-defined functions:
User-defined function means the user will define those functions as per user need.
Now using the def keyword let's create a function.
Here we have ‘fun’ as our function name followed by parenthesis. Then we have the print statement.
After creating a function, we should call it by using the name of the function followed by a parenthesis that contains the parameters of that particular function.
As we can see in the above example we have to call the function i.e. fun(), and now it will execute the print statement.
Here we have defined the function sum(a,b), it takes parameters a & b, calculates their sum, and prints the result. Then we call the function sum(10,20) these values are passed as arguments in the function. The function performs the addition and prints the final result.
- A simple Python function to check whether x is even or odd.
In the above program, we have used conditional statements to check whether the given number is even or odd.
- Finding a maximum of two numbers.
Let’s write a program on the real-life example we took before:
Calculating the area of a rectangle:
The function total_area takes width and height as inputs and returns the calculated area. Now we will give the actual measurement values to the width and height that is required for the fence. Then we call the function total_area followed by the width and height that is provided. This reduces time and math errors.
Arguments are specified after the function name inside the parentheses. We can add as many arguments as we want but they should be separated with a comma.
Positional Arguments:
These are arguments that need to be included in a proper position or order. The first positional argument needs to be listed first when the function is called and so on.
Keyword Arguments:
They are related to function calls. When the keyword arguments are used in a function call, the caller identifies the arguments by the name of the parameter.
In the below case, if we pass a value in the function call, it will override the default value.
These are also known as varargs that allow a function to accept several arguments.
There are two ways to define these arguments in a function.
In the above example, in the function add(n1, *n2), n1 takes one argument and the arbitrary number of additional arguments is grouped into a tuple called n2. n2 calculates all the values that are passed after n1.
Then we call the function add() with n1 as 5 and multiple values 10,20,30,40,50 are passed as additional arguments. The function calculates the sum of all the values present in n2 (which is 10,20,30,40,50) and then adds to n1.
In the above example, we have defined a function called
print_info(** kwargs) using **kwargs
We use this type of function when we want to handle unknown named arguments and process them as a collection of key-value pairs.
A recursive function is a function which calls itself. The recursive term can be defined as the process of defining something in terms of itself.
A recursive function needs to have a condition to stop calling itself so we use an ‘if’ statement.
In the above example, we can see that the function sum(n) is a recursive function that calculates the sum of all positive numbers starting from 1.
So, here when we call sum(2), it recursively adds 2+1+0, resulting in the return value of 3.
A function without a name is known as an anonymous function. It is not defined using the def keyword instead we use the lambda keyword.
lambda keyword is used to create a lambda function <argument_list> This is a list of arguments that are accepted by the lambda function and should be separated by a comma. It is similar to defining of argument in a regular function. : (colon) is used to separate the argument list and the lambda expression. expression is a single expression that the lambda function evaluates and returns. It is an operation that the lambda function performs.
In the above example:
1.f=lambda x:x+x: here, a lambda function is created and assigned to a variable f. Then lambda function takes an argument as x and returns the result of x+x.
2. f(5): this line calls the lambda function f with the argument 5 When argument 5 is passed it substitutes x and the function evaluates 5+5 resulting in 10.
In this blog, we have learned why functions are important in the Python programming language. We learned about the advantages and disadvantages of functions, types of functions that are built-in functions, and user-defined functions. We saw how to create and call a function with an example, and then we learned about function arguments and types of arguments with examples of each. Lastly, we have seen other types of functions such as recursive functions and anonymous functions with examples of each.