Python - Function and its types

The function is a block of a code that can be reused, it only runs when called. we can also pass some parameters to the functions which are called arguments. You can define a function using the def() statement.

def sq(a):
print( a**2 )

Using return

We can also use return in the place of print the only difference is that the code written inside the function after return will not be executed. and you have to use print() while calling the function.

def sq(a):
return( a**2 )

you can also use more than one arguments at the same time.

def sum(a,b):
return( a+b )

There are several types by which arguments can be passed, they are Default arguments, Keyword arguments and Arbitrary arguments.

Default arguments:

Default arguments in Python functions are those arguments that take default values if no other values are passed to these arguments from the function call. The below code is an example of how to define a function with one default argument.

you can also pass values through the default arguments and while defining you must place the default argument at last.

def sum(i=2,b): 
result = i+b
return result

Keyword arguments:

Keyword arguments are how you call a function. Default values are how a function is defined. Default arguments mean you can leave some parameters out. Keyword arguments mean you don’t have to put them in the same order as the function definition.

def key(a=5,b=7):
return c,d

Arbitrary arguments:

If you want to pass an iterable argument through a function you can use this syntax is * symbol before the argument.

def sq(*a):
return a**2

Higher-Order Functions:

A function is called Higher-Order Function if it contains other functions as a parameter or returns a function as an output. There are three built-in higher-order functions namely,

  1. Map
  2. Filter
  3. Reduce


The map() function iterates through all items in the given iterable and executes the function we passed as an argument on each of them.

def sq(*a):
return a**2


Reduce doesn’t create a new list with that list we passed instead it returns a single value.

def sum(a,b):
return a+b


It filters the array and returns only the elements of that array which passed that given condition.

def odd(a):
return a%2!=0

Lambda function:

They are also known as an anonymous function, not defined with any name. For simple one or two-line functions we can use lambda functions instead of the traditional methods.

lambda arguments: expression

x = lambda a : a + 10