User define Function in Python

A function is a block of code that takes input(s), performs some computation and returns a result.
Syntax to create a function is :

def func(formal parameters):
     '''doc string'''
     return value

For example to create a function to find prime factors of a given number is

def prime_factorization(num):
     ''' Find prime factors of a given number '''
     factors = []
     divisor = 2
     while num > 1:
         if num % divisor == 0 :
             num = num // divisor
             divisor += 1
     return factors

Documentation Strings tells the purpose of function

 Find prime factors of a given number 

Calling a Function
To call a function, use the function name followed by actual parameters inside parenthesis.

 [2, 2, 3, 3]

Default parameter
We can also set a default value for parameter, so if no value is passed assigned to parameter while calling function, then default value gets assigned to function

def greet(occassion = "Hi"):
     if occassion.capitalize() == "Birthday":
         message = "Happy B'day!!"
     elif occassion.capitalize() == "Anniversary":
         message = "Happy Anniversary"
         message = occassion
     return message

Calling greet() with parameter value

 Happy B'day!!

Calling function without parameter will take default value of parameter


Pass by Reference or pass by value?
One important thing to note is, in Python every variable name is a reference.
When we pass a variable to a function, a new reference to the object is created.
So parameters in a function are passed by reference

Variable length arguments
If we do not know how many arguments will be passed to function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly:

def sum_of_squares(*args):
     s = 0
     for arg in args:
         s += arg ** 2
     return s

args is a tuple, it will contain all parameters which are passed to function while calling.
Below we are calling function with 3 parameters

Below we are calling function with 4 parameters

Keyword arguments
If we specify ** before parameter name in function definition, parameters are passed as a dictionary

def sum_of_exponent(**kwargs):
     power = kwargs['exponent']
     n_list = kwargs['nums']
     s = 0
     for n in n_list:
         s += n ** power
     return s

kwargs is a dictionary, and parameters are passed as a key,value pair of dictionary.

print(sum_of_exponent(exponent=2, nums=[1,2,3]))

We can also change order in which parameters are passed
print(sum_of_exponent(nums=[1,2], exponent=3))

Shekhar Pandey

Add comment