For more Subjects
https://www.studymedia.in/fe/notes
UNIT: III               Functions and Modules                                         Lectures:
                                                                                       08 Hrs
 •   Need for functions:
 •   Function: definition, call, variable scope and lifetime, the return statement.
 •   Defining functions, Lambda or anonymous function,
 •   documentation string,
 •   good programming practices.
 •   Introduction to modules,
 •   Introduction to packages in Python,
 •   Introduction to standard library modules.
                           Other Subjects: https://www.studymedia.in/fe/notes                     1
                                    Function
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
Defining a Function
•Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
• The code block within every function starts with a colon (:) and is indented.
• The statement return *expression+ exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
                         Other Subjects: https://www.studymedia.in/fe/notes                      2
                                   Function
Syntax:
def function_name (parameter) :
def marks the start of function
Function_name to uniquely identify a function.
Argument to pass a value in function
colon(:) to mark end of function header
                        Other Subjects: https://www.studymedia.in/fe/notes   3
Other Subjects: https://www.studymedia.in/fe/notes   4
                              Function Type
THERE ARE TWO TYPES OF FUNCTION IN PYTHON
BUILT-IN FUNCTION:
Example: print(), input(), eval().
USERDEFINE FUNCTION:
Example: def my_addition(x,y):
sum = x + y
return sum
                      THERE ARE 68 BUILT-IN FUNCTION VERSION 3.4.
                          Other Subjects: https://www.studymedia.in/fe/notes   5
Other Subjects: https://www.studymedia.in/fe/notes   6
Other Subjects: https://www.studymedia.in/fe/notes   7
Return Statement
   It is statement to return from a function to its
   previous function who called this function.
   After return control goes out of the current
   function.
   All local variables which were allocated memory in
   current function will be destroyed.
   Return statement is optional in python.
   Any function can return multiple arguments.
               Other Subjects: https://www.studymedia.in/fe/notes
Return Statement
 Example
   return               #This returns none value
   return None           #This returns none value
   return a, b          #This returns two values
   return a             #This returns single value
   These all are valid examples of a return statement.
                 Other Subjects: https://www.studymedia.in/fe/notes
• Position
• Keyword
• Default
• Variable length
• lambda
                    Other Subjects: https://www.studymedia.in/fe/notes   10
Other Subjects: https://www.studymedia.in/fe/notes   11
Other Subjects: https://www.studymedia.in/fe/notes   12
Other Subjects: https://www.studymedia.in/fe/notes   13
Other Subjects: https://www.studymedia.in/fe/notes   14
Anonymous Functions / Lambda Functions
   Functions containing only single operation can be
   converted into an anonymous function.
   ‘Lambda’ is the keyword used to create such anonymous
   functions.
Syntax
  Lambda < space > <parameter> : < operation >
Example
   my_addition = lambda x, y : x + y
   print(“addition is ”, my_addition(20, 30))
Output = 50
               Other Subjects: https://www.studymedia.in/fe/notes
Other Subjects: https://www.studymedia.in/fe/notes   16
Variable Scope and Lifetime
1. In functions, there are two kinds of variables, local and
   global.
Local Variables / Objects :
2. Variables or objects which are used only within given
   function are local variables or local objects.
3. Local objects include parameters and created in a given
   function.
Example
  In following code, mult() function has two local variables
  Local variable ‘a’ and local variable ‘b’.
                Other Subjects: https://www.studymedia.in/fe/notes
Global variables / objects
    1. Objects which can be accessed throughout the
       script/program are global variables or objects.
    2. Global variables or objects are created in python script
       outside any function.
    3. Global objects are available after “global” keyword
       defined in the script.
                  Other Subjects: https://www.studymedia.in/fe/notes
Global variables / objects
  1. Reading Global variable value
  Example
     In following example global variable is accessed for
     printing / reading purpose.
     No modification to global variable is done here.
                 Other Subjects: https://www.studymedia.in/fe/notes
Global variables / objects
#No modification in global variable id made
def add_gv(a,b):
   c=a+b+gv
   print("in function value of gv is =",gv)
   print("The addition is :",c)
gv=100
print("The initial value of gv =", gv)
add_gv(10,20)
print("After function value of gv =",gv)
                 Other Subjects: https://www.studymedia.in/fe/notes
Global variables / objects
Modification of Global Variable Value
   ‘global’ keyword is used to modify a global variable inside a
   function.
Example
   In following example “global” keyword is used inside the
   function.
   Now global variable can be modified within the function.
   Modifications made in the function (after using “global”)
   will stay after the function as well.
                 Other Subjects: https://www.studymedia.in/fe/notes
Global variables / objects
#Modification in global variable is made
def add_gv(a,b):
  global gv
  gv=150
  print(gv)
  c=a+b+gv
  return c
  gv=100
print(gv)
x=add_gv(10,20)
print(x)
print(gv)
                   Other Subjects: https://www.studymedia.in/fe/notes
Documentation String
    In python, programmer can write a documentation
    for every function.
    This documentation can be accessed by other
    functions.
  Advantage of Document string
    It is useful when we want to know about any
    function in python.
    Programmer can simply print the document string
    of that function and can know what that function
    does.
              Other Subjects: https://www.studymedia.in/fe/notes
Documentation String
             def func( ):
               """Welcome to Coulomb"""
               return
             print(func.__doc__)
             Other Subjects: https://www.studymedia.in/fe/notes
Standard Libraries in Python
 1. Math (import math)
     This is a package for providing various functionalities
     regarding mathematical operations.
 2. Random (import random)
     This is the module which supports various functions for
     generation of random numbers and setting seed of random
     number generator.
 3. Numpy (import numpy)
     This is a package in python which supports various
     numeric operations. It supports multidimensional arrays or
     matrices and their calculations.
 4. Scipy (import scipy)
    This is the package for various scientific computations.
                  Other Subjects: https://www.studymedia.in/fe/notes
Introduction to Modules
    Modules make python programs re-usable.
    Every python code (.py) file can be treated as a
     module.
    A module can be accessed in other module using
     import statement.
    A single module can have multiple functions or
     classes.
    Each function or class can be accessed separately
     in import statement.
                Other Subjects: https://www.studymedia.in/fe/notes
Introduction to Modules
 Example to create your own module
    Create a file named sample.py in your directory.
    Write function add() in it. (as we have seen in
     previous sections)
    Now create another file trial.py in same directory
    In trial.py write
    import sample.add
     print(“addition is “, sample.add(10,20))
    Now run trial.py.
    Now the output will be 30.
                Other Subjects: https://www.studymedia.in/fe/notes