UNIT-III
Functions &
Modules
Topics to be covered:
Functions:
Defining a function, calling a function, Types of
functions, Function Arguments, Anonymous
functions, Global and local variables
Modules:
Importing module,
Math module,
Random module,
Packages
Functions:
In Python, function is a group of related statements that
perform a specific task.
Functions help break our program into smaller and
modular chunks.
As our program grows larger and larger, functions make
it more organized and manageable.
If a group of statements is repeatedly required then it is
not recommended to write these statements every time
separately.
We have to define these statements as a single unit and
we can call that unit any number of times based on our
requirement without re writing.
This unit is nothing but function.
The main of advantage of functions is code is Reusability.
Note: In other languages functions are also known as
methods,procedures,subroutine etc.
Advantage of functions in python
There are the following advantages of C functions.
By using functions, we can avoid rewriting same
logic/code again and again in a program.
We can call python functions any number of times
in a program and from any place in a program.
We can track a large python program easily when
it is divided into multiple functions.
Reusability is the main achievement of python
functions.
Python supports 2 types of functions
[Link] in Functions
[Link] Defined Functions
Anonymous functions
[Link] in Functions:
Functions that are built into Python.
The function which are coming along with python
software automatically, are called built-in
functions or pre defined functions.
Example:id(),type(),input(),eval() etc…
[Link] Defined Functions:
The functions which are developed by programmer explicitly
according o business requirements, are called User defined
functions.
Defining a Function
Here are simple rules to define a function in Python.
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 first statement of a function can be an optional
statement - the documentation string of the function or
docstring.
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.
Syntax of Function:
def function_name(parameters):
"""docstring""“
statement(s)
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming
follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to
a function. They are optional.
A colon (:) to mark the end of function header.
Optional documentation string (docstring) to describe
what the function does.
One or more valid python statements that make up the
function body. Statements must have same indentation
level (usually 4 spaces).
An optional return statement to return a value from the
function.
Parameters:
Parameters are inputs to the functions.
If a function contains parameters, then at the
time of calling , compulsory we should provide
values otherwise we will get error.
Return Statement:
The return statement is used to exit a function
and go back to the place from where it was called.
Function can take input values as parameters and
executes business logic, and returns output to the
caller with return statement.
Syntax of return:
return [expression_list]
This statement can contain expression which gets
evaluated and the value is returned.
If there is no expression in the statement or the
return statement itself is not present inside a
function, then the function will return the None
object.
Returning multiple values from a function:
In other languages like C,C++ and java, function
can return atmost one value.
But in python, a function can return any number
of values.
Function Arguments:
There are 4 types of Actual arguments are followed in
python.
[Link] arguments
[Link] arguments
[Link] arguments
[Link] length arguments.
[Link] arguments:
These are arguments passed to function in correct positional
order.
def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)
The number of arguments and position of arguments must
be matched.
If we change the order then the result may be changed.
[Link] arguments:
We can pass argument values by keyword i.e by
parameter name.
Here the order of arguments is not important but number
of arguments must be matched.
Python allows us to call the function with the keyword
arguments. This kind of function call will enable us to
pass the arguments in the random order.
The name of the arguments is treated as the keywords
and matched in the function calling and definition.
If the same match is found, the values of the arguments
are copied in the function definition.
Note:
We can use positional and keyword arguments
simultaneously.
But first we have to take positional arguments and then
keyword arguments, otherwise we will get syntax error.
Default argument:
If we are not providing values then automatically
it takes default arguments.
Some times we can provide default values for
positional argumnets.
Declaring a variable with value then we can say
“default argument”
If we are not passing any name then default value
will be considered.
Note: After default arguments we should not take
non default arguments.
Variable Length Arguments or Arbitrary
Arguments:
Some times we can pass variable number of
arguments to our function, such type of
arguments are called Variable length arguments.
For two and three
Ex:
arguments every time
special function we have
def sum(a,b): to define
print(a+b)
def sum(a,b,c):
print(a+b+c)
By using above method code is increasing.
No overloading in python.
We have to use different name as methods.
To overcome this problem we have variable length
arguments.
We can declare a variable length argument with *
symbol as follows
Syntax:
def f1(*n):
We can call this function by passing any number
of arguments including Zero number.
Internally all these values are represented
in the form of tuple.
Note: We can mix variable length arguments with
positional arguments.
Note: After variable length argument, if we
are taking any other arguments then we
should provide values as keyword
arguments.
Note: we can declare key word variable
length argument also.
For this we have to use **.
Syntax:
def f1(**n): any number of key value pairs we
can pass
[Link] keyword arguments we
should not take positional
arguments.
[Link] default arguments we
should not take non-default
arguments.
[Link] variable length
arguments if we are taking
normal arguments, compulsory
we should provide value by
keywords.
Anonymous Functions:
Some times we can declare the functions without
any name, such type of nameless functions are
called anonymous functions or lambda functions.
Instant use(one time usgae)
Normal function declaration:
def squareit(n):
return n*n
In anonymous function we can define by using
lambda keyword.
Syntax:
Lambda input argument: expression
By using Lambda functions we can write
very concise code so that readability of the
program will be improved.
Note:
Lambda functions internally returns expression
value and we are not required to write return
statement explicitly.
Some times we can pass function as argument to
another function.
In such case lambda functions are best choice.
We can use lambda functions very commonly with
filter(),map() and reduce() functions because
these functions expect function as arguments.
Module: Group of functions
Package: Group of Modules
Library: Group of Packages
Recursive Function:
In Python function, recursion is when a function
calls itself.
Advantages:
Reduce length of the code
Improve readability
We can solve complex problems.
Factorail(3)=3*Fact(2)
=3*2*Fact(1)
Facr(n)=n*Fact(n-1)
We can use Lambda functions very commonly
with filter(), map() and reduce() functions
because these functions are expect function as
argument.
filter() function:
We can use filter function to filter values from the
given sequence based on some condition.
Syntax:
filter(function, sequence)
Where function argument is responsible to
perform conditional check sequence can be list or
tuple or string.
map() function:
For every element present in the given sequence,
apply some functionality and generate new
element with the required modification.
For this requirement we should go for map()
function.
Syntax:
map(function , sequence)
The function can be applied on each element of
sequence and generates new sequence.
reduce() function:
Reduce function reduces sequence of elements
into a single element by applying the specified
function.
Syntax:
reduce(function ,sequence )
reduce() function present in functools module and
hence we should write import statement.
Function Aliasing:
For the existing function we can give anther
name, which is nothing but function aliasing.
If we delete one name still we can access that
function by using alias name.
In the above example only one function is
available but we can call that function by using
either wish name or greeting name.
If we delete one name still we can access that
function by using alias name.
Nested Functions:
A function which is defined inside another
function is known as nested function.
Nested functions are able to access variables of
the enclosing scope.
In Python, these non-local variables can be
accessed only within their scope and not outside
their scope.
In the above example inner(0 function is local to
outer() function and hence it is not possible to call
directly from outside of outer() function.
A function can return another function.
Function Decorators:
Decorator is a function which can take a function
as argument and extend its functionality and
return modified function with extended
functionality.
New(add some
Input function Decorator functionality)
Inner()
Output Function with
Decorator
Input function Extended
Function
functionality
The main objective of decorator functions s we
can extend the functionality of existing functions
without modifies that function.
This is also called metaprogramming as a part
The above function prints always same output for
any name.
But if we want to modify this function to provide
different message if name for example “IT-C”.
We can do this without touching function by suing
decorator.
In above program whenever we call function
automatically décor function will be executed.
Decorator chaining:
We can define multiple decorators for the same
function and all these decorators will from
Decorator Chaining.
Ex:
A group of lines with some name is called a
Function.
A group of functions saved to a file, is called
Module
A group of Modules is nothing but Library.
Python module is nothing but a piece of code.
Exiting the interpreter destroys all functions and
variables we created. But when we want a longer
program, we create a script.
With Python, we can put such definitions in a file, and
use them in a script, or in an interactive instance of the
interpreter. Such a file is a module.
A python module can be defined as a python program
file which contains a python code including python
functions, class, or variables.
In other words, we can say that our python code file
saved with the extension (.py) is treated as the module.
We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize
the code in a logical way.
To use the functionality of one module into another, we
must have to import the specific module.
A group of functions, variables and classes
saved to a file, which is nothing but module.
Every python file(.py) acts as module.
Demo module contains one variable and 2
functions.
If we want to use members of module in our
program then we should import that module .
import modulename
We can access members by using module
name.
modulename. Variable
[Link]()
Whenever we are using a module in our
program, for that module compiled file will
be generated and stored in the hard disk
permanently.
Renaming a module at the time of import
(module aliasing):
from…import:
We can import particular members of module by
using from…import.
The main advantage of this is we can access
members directly without using module name.
We can import all members of a module import*
from Demo import*
Various possibilities of import:
import modulename
import module1,module2,module3
import module1 as m
import module1 as m1,module2 as m2,module3
from module import member
from module import member1,member2,member3
from module import member1 as x
from module import*
Reloading a module:
By default module will be loaded only once even
though we are importing multiple times.
In the above program test module will be
loaded only once even though we are importing
multiple times.
The problem in this approach is after loading a
module if it is updates outside then updates
version of module1 is not available to our
program.
We can solve this problem by reloading module
explicitly based on our requirement.
We can reload by using reload() function from
imp module.
The main advantage of explicit module
reloading is we can ensure that updates version
is always available to our program.
Finding members of module by using dir() function:
Python provides inbuilt function dir() to list out all members of
current module or a specified module.
dir()To list out all members of current module.
dir(moduleName)To list out all members of specified module.
So, when you call dir() in your code, it returns a list of all
names in the current scope, including default attributes
provided by Python (__annotations__, __builtins__, etc.) and the
names you've defined (x, y, f1).
For every module at the time of execution
Python Interpreter will add some special
properties automatically for internal use.
The special variable__name__:
For every Python program, a special varaible
__name__ will be added internally.
This variable stores information regarding
whether the program is executed as an
individual program or as a [Link] the
program executed as an individual program
then the valu of this varaible is __main__
If the program executed as a module from some
other program then the value of this variable is
the name of module where it is defined.
Hence by using this __name__ variable we can
identify whether the program executed directly
or as a module.
Math module:
Python provides inbuilt module math.
Tis module defines several functions which can
be used for mathematical operations.
[Link]()
[Link]()
[Link]()
[Link]()
[Link](x)
[Link](x)
[Link](x)
Note: We can find help for any module by using
help() function
random module:
This module defines several functions to
generate random numbers.
We can use these functions while developing
games, in cryptography and to generate random
numbers on fly for authentication.
[Link]():
This function always generates some float value
between 0 and 1 (not inclusive)
0<x<1
[Link]():
To generate random integer between two given
numbers(inclusive)
[Link]():
It returns random float values between 2 given
numbers (not inclusive)
random()in between 0 and 1(not inclusive)
randint(x,y)in between x and y(inclusive)
uniform(x,y)in between x and y (not inclusive)
randrange([start],sop,[step]):
Returns a random number from range
Startx<stop
Start argument is optional and default value is 0
Step argument is optional and default value is 1
choice():
It wont return random number
It will return a random object from the given list
or tuple.