Python Practise Function

FUNCTIONS

Introduction: 

  • A function is a block of code which runs when it is called.

  • Function helps to break the program into smaller chunks.

  • As program grows larger and larger functions make it more organised and manageable.

  • Functions avoids repetitions and makes the code reusable. 

  • Syntax:

def func_name(parameters): ---function definition

Statements ---function body

Return data ---return/exit point of function

data = func_name(arguments) ---function call



















Types of functions:

There are mainly two types of functions.


1. pre defined functions or built in functions:

the functions which are designed while python designing are called 

built in functions.

ex:      id() --------returns address of the object

type()------returns type of the object(data type)

input()----accepts input from keyboard and returns to program

print()----returns print statement to the console

ord()-----returns ASCII value of any character

chr()-----return character of specified ASCII value

bin()----returns binary value of integer


2. user defined function:

the functions designed by programmer as per customer requirement is 

called user defined functions.


Return type:

-return keyword is used to return output of the function.

-it symbolises exit/end of the function body

-using return is not mandatory.

-it will exit the function execution and takes the console to the point 

from where it called.

-after return statement execution, no other statements will get execute.

-it can return any value, multiple values or None.

- syntax: return object/data

return o1, o2, o3.......object_n---------it will return all the values by

packing inside tuple.


  Note: 

when program needs output of particular function to be act as input for any other operation or if we want to bring output of the function block outside it, we need return.


Arguments and Parameters:

these are inputs to any function. if a function contains any parameters, then while 

calling mandatorily, we have to pass values i.e., arguments. Hence we can say parameters are containers of arguments.


Difference between parameters and arguments:

1.the values that are declared within a function when the function is called are called as arguments where as the variables that are defined when function is declared are called parameters.
2. args will be used to call a function, parameters acts as header of the function definition.
3. args will send values to function def by calling it, where in parameters accept or catch the values from function call.
4. args are always global to the function, but parameters are local.
5. arguments--actual parameter(user input) and parameters---Formal parameters(identifier).


Types of arguments or parameters:

1. positional parameter

2. keyword parameter

3.combination of positional and keyword

4.keyword and positional only parameters

5. variable positional arguments

6. variable keyword arguments




  1. positional parameter:

  • number of positions should be fulfilled (arguments = values)

  • positions will be fixed.

  • to mandate positional only arguments, we use “/”

def add(a,b, /):

     c = a+b

     return c

res = add(4,0)

print(res)



  1. keyword parameter:

  • arguments are key value pair.

  • arguments will take the values in function definition if no values passed in function call.

  • it’s not mandatory to pass fixed number of arguments in function call.

  • when we pass some values from function call it will override the values in definition.

  • to mandate the keyword arguments * will be used.

def add(a = 10, b = 20):

c = a+b

return c

res = add(5)

print(res)

    3.combination of positional and keyword arguments:

  • combination of both positional and keyword arguments.

  • always keep positional arguments first these are also called as default arguments.

  • number of positional arguments should be fulfilled

  • after positional arguments we can pass keyword arguments.

  •  / should be given after the arguments.

  •  * should be given before the arguments

def add(a, /, *, b = 10):

c = a + b

return c

res = add(5)

print(res)

4.keyword and positional only arguments:

  • Mandating arguments as only positional or only keyword by using / or *


5. variable positional arguments:

  • variable positional argument:

  • all arguments should be positional only

  • length of arguments can be anything.

  • it will accept the arguments and pack them inside tuple.

def func(*args):

res = sum(args)

 return res                                                                                                      res = func(2,3,4,5)                                                                                                   print(res)

6. variable keyword arguments:

  • variable keyword argument:

  • all arguments should be keyword only

  • length of arguments can be anything.

  • it will accept the arguments and pack them inside dictionary.

def func(*kwargs):

 res = sum(kwargs.values())

return res                                                                                                  res = func(a=2, b=3, c=4, d=5)                                                                                                   print(res)

Note:  

  • *args is performing packing operation if we use it in function definition, where as it acts as unpacking operator.

  • if we use it in function calling.

  • print() is inbuilt function where unpacking is automatic.


Default parameter:

  • default parameter indicate that the function argument will take default value if no values given by user during function call.

  • default value can be given in function definition by using assignment operator.

  • example:

def func(msg = "no message passed"):

    print(msg)

 func()




Function annotations:

  • annotations are only data type(input/output) hints.

  • it does not enforce type checking of data.

  • syntax:

def func(args1:datatype, args2:datatype)

statements                                                                                                                   return type

scope of variables (a life cycle of variable from initialising to deletion)


1. local variable:

  • a variable which is created inside function is called local variable.

  • it cannot be accessed outside of the function.

  • ex: def func():

var1 = value

2.global variable:

  • a variable which is created independently is called global variable.

  • this can be accessed and used anywhere throughout the program.

  • it can be accessed inside the function and can be utilised but cant be modified.

  • in order to modify global variable inside the function we need to use global keyword.  (Conversion of local var to global)

a = 10

def func():

global a

a += 20

print(a)


3.nonlocal variables:

  • non local scope variables are those which are neither local nor global(inside nested functions)

  • if a nested function have to access and modify the variable outside of the function then nonlocal keyword is used. (Conversion of nonlocal var to local)

def spam():

a = 10

def newspam():

nonlocal a

a += 10


Note:

  • nonlocal variables can be localised by using nonlocal keyword, and can be globalised by using global keyword.

  • local variables can be globalised using global keyword.

  • global keywords can be accessed throughout the program anywhere until we have same named variables in program.

  • we cannot chain single variable nonlocal to local and local to global at a time.


recursion:

  • a function that calls itself is called recursive function.

  • we can reduce number of repeated codes.

  • improves readability.

  • solving complex problems becomes easy.

  • we can avoid using multiple loops again and again.

anonymous functions:

  • these are nothing but inline functions (written in one line)

  • these are nameless functions so we cannot call these functions again and again

  • static in nature.

  • while writing these functions we don’t define them so no use of def keyword.

  • we can pass any number of arguments.

  • we cannot access global variables inside these functions.

  • it always returns expression not a value.

  • we use "lambda" keyword to write anonymous functions so they are also called as lambda expressions.

  • we can directly print output by using print function else we can also store lambda expression in any variable.

  • syntax:

var_name = lambda [args1, args2,.......argsn] : expression

Note:

  • lambda functions internally returns expression so need not to give return type explicitly.

  • sometimes we can pass functions as expression to lambda functions, and also arguments to lambda functions.

  • we can use lambda functions with filter(), map(), reduce() methods effectively, because these methods expect function itself as argument.




map():

  • map() will apply a function to all the items or elements or characters present inside the iterable.

  • returns map object.(map is a class)

  • for every element present in the iterable it applies some functionality and generates a new element with the required modification.

  • it can be applied for more than one iterable, but the iterables should be of same length.

  • its functionality always starts with zeroth index to nth index.

  • it will work with sequences only(string, list, tuple)

  • syntax:

map(funtionality_to_be_applied, iterable)

filter():

  • filter accepts 2 arguments, one should be function and another should be iterable.

  • filter() is an elegant way to filter out all the elements of the iterable or sequence for which function returns true.

  • filter() creates list of elements for which function returns true. ie return type is list.

  • unlike map() only one iterable is required.

  • filter() will consider only the inputs which are yielding true or nondefault output.

  • only one iterable is accepted by filter() so always function should accept only one argument.

  • syntax:

filter(function,iterable)


Comments

Popular posts from this blog

Speech Emotion Recogination