Python - Function and its types

Nandhabalan Marimuthu
2 min readApr 15, 2021

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 )
sq(5)
25

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 )
print(sq(5))
25

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

def sum(a,b):
return( a+b )
print(sum(5,10))
15

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
print(sum(4)))
6

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):
c=a*2
d=b*3
return c,d
print(key())
(15,21)

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
print(sq(1,2,3,4,5))
(1,4,9,16,25)

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

map()

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
a=[1,2,3,4,5]
print(map(sq,a))
[1,4,9,16,25]

reduce()

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
a=[1,2,3,4,5]
print(map(sq,a))
15

filter()

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

def odd(a):
return a%2!=0
a=[1,2,3,4,5]
print(map(odd,a))
[1,3,5]

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
print(x(5))
15x= lambda a: a**2
print(x(7))
49

--

--