Data Analytics

WHY FUNCTIONS ARE IMPORTANT IN PYTHON PROGRAMMING LANGUAGE?

Neeta S Karadi

Neeta S Karadi

Dec 27th - -2 min read

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.

Functions

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:
function syntax.png

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.

- Advantages of Using Functions

  • It is easy to read and understand.
  • We can reuse the code multiple times.
  • It is easier to organize the code.
  • Complex code can be broken into simpler code.

- Types of Functions

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.

- Creating a Function

Now using the def keyword let's create a function. creating a function.png

Here we have ‘fun’ as our function name followed by parenthesis. Then we have the print statement.

- Calling a function

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. calling a function.png

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.

- Function with Parameters

function with parameters.png

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.

Examples:

- A simple Python function to check whether x is even or odd. even and odd.png

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. maximum of two.png

Let’s write a program on the real-life example we took before: Calculating the area of a rectangle: total area.png

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.

- Function Arguments in Python

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.

- Types of Arguments

  1. Positional Argument
  2. Keyword Argument
  3. Default Argument
  4. Variable-Length Argument
  • 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. positional argument.png

  • 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. keyword argument.png

  • Default Arguments:
    It is an argument that assumes a default value if a value is not provided in the function call for that argument. default argument 1.png

In the below case, if we pass a value in the function call, it will override the default value. default argument 2.png

- Variable-length Arguments:

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.

  1. args
  2. kwargs
  • args:
    The asterisk() before the parameter name allows the function to accept any number of positional arguments. The arguments passed to *args are collected into a tuple within the function. args.png

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.

  1. sum=0 means initializing the variable sum to ‘0’.
  2. for i in n2 means looping through each element in the iterable n2.
  3. sum+=1 here it adds the current element ‘i’ to the variable sum.

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.

  • kwargs:
    The double asterisk() before the parameter name, allows the function to accept any number of keyword arguments. The arguments passed to ** kwargs are collected into a dictionary within the function. kwargs.png

In the above example, we have defined a function called
print_info(** kwargs) using **kwargs

  • ** kwargs: this syntax is used to define a function that allows to passing of any number of keyword arguments and these arguments are collected in the form of a dictionary named kwargs.
  • for key, value in kwargs. items(): this loop iterates through key-value pairs in the dictionary ‘kwargs’ and prints each pair.
  • As we can see the function print_info() is called twice.
  1. print_info(name="John", age=25): in this function, we have passed two keyword arguments i.e. name and age. So, it prints:

kwargs with 2 arguments.png

  1. print_info(city="New York", country="USA", profession="Engineer"): In this function we have passed three arguments i.e. city, country, and profession. So, it prints: kwargs with 3 arguments.png

We use this type of function when we want to handle unknown named arguments and process them as a collection of key-value pairs.

- Recursive Function

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. recursive function.png

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.

  • Inside the function:
  1. if n > 0: This is a conditional statement that says if n is greater than 0 then proceed with the calculation.
    2.return n + sum(n-1) this line is a recursive call to the sum() function. It adds the current values of n to the sum of all positive integers less than n i.e. n-1.
  2. It keeps reducing n by1 each time until n becomes 0.

For example:

recursive function example.png So, here when we call sum(2), it recursively adds 2+1+0, resulting in the return value of 3.

-Anonymous Function

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.

  • Syntax lambda function.png

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.

Example:

lambda function example.png

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.

CONCLUSION

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.

about the author

Neeta is passionate about data analytics and eager to dive deeper into the world of machine learning. Python's simplicity captivates her, making it the perfect language for her interests. She's thrilled to embark on diverse projects and explore applications within these dynamic fields.