In Python, functions are a reusable blocks of code that perform a specific task. They allow you to encapsulate logic, promote code reusability, and improve the organization of your code.

The syntax of declaring a function is:

Below is a function with no parameters

def func_name() :

        statement_1

        statement_2

        statement_3

func_name()  ## Calling the function


Examples:

Here's a function with parameters that accepts and prints the name entered by the user

def name ( a ) :

        print ( a )

name ( input ( " Enter the name " ) )


Here's a function with return value and parameters

def add ( a , b ) :

        return a + b

c = add ( 4 , 5 )

print ( c )


Let's look at the various types of functions:

1. Lambda Function ( Single line function )

Below is a function to square a number

x = int ( input ( " Enter a number " ) )

ans = lambda x : x ** 2

print ( ans )


To add two numbers:

x = 5 , y = 10

sum = lambda x , y : x + y

print ( sum )


2. Map Function

It is a higher order function

Syntax -- print ( iterable ( map ( func_name , iterable ) ) )


Example :

To print the square of the elements in the list -

lis = [ 1 , 2 , 3 , 4 ]

def fun ( x ) :

        return x **2

print ( list ( map ( fun , lis ) ) )


We can do all this in a single line as follows:

lis = [ 1 , 2 , 3 , 4 ]

print ( list ( map ( lambda x : x ** 2 , lis ) ) )


3. Filter Function

For instance a filter function can be used to filter and separate odd and even numbers from a list as follows

lis = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]

odd = list ( filter ( lambda x : x % 2 != 0 , lis ) ) )

even = list ( filter ( lambda x : x % 2 == 0 , lis ) ) )

print ( odd )

print ( even )


4. Reduce Function

The reduce() function in Python is part of the functools module and is used to perform a rolling computation on a sequence of elements. It continually applies a function to pairs of elements from left to right until only a single value remains.

Example:

To find the sum of elements in a list:

lis = [ 1 , 2 , 3 , 4 , 5 ]

from functools import reduce      ## need to import the function

def fun ( x , y ) :

        return x + y

print ( reduce ( fun , lis ) )


Recursive functions

A function that calls itself is a recursive function

Example:

Below is a code that finds factorial of a 5 using recursion

def fact ( n ):

    if ( n == 0 ):

        return 1

    else:

        return n * factorial ( n - 1 )

print ( fact ( 5 ) )

Output:

120


Doc String

Documenting the purpose of execution of a function


Example:

def square ( n ):

    ''' Returns square of a number ''' # This is the doc string

    return n**2

print ( square.__doc__ )

square ( 2 )

Output:

Returns square of number

4