Unit-IV
Functions & Modules
Unit-IV Functions & Modules
Unit-IV
Functions & Modules
Introduction to functions: function definition, Types of Functions:
Built-in functions, User defined functions: Defining, Calling, return
statement, Types of arguments: Positional, keyword, default and variable
length arguments, Variable scope: Local, Global variables, Lambda
Function/ Anonymous function, Recursive Functions.
Introduction to Modules: Built-in and user-defined.
Unit-IV Functions & Modules
Need for functions
• 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.
• Python provides many built-in functions like print(), etc. but you can also create your
own functions. These functions are called user-defined functions.
Following are advantages of functions in python
✔ Reducing duplication of code.
✔ Decomposing complex problems into simpler pieces.
✔ Improving clarity of code.
✔ Reuse of code.
✔ Information hiding.
Unit-IV Functions & Modules
Defining a Function
Syntax Any input parameters or arguments
Function blocks begin with the should be placed within these
keyword def followed by the function parentheses.
name and parentheses ( ( ) ).
def functionname( parameters ): The code block
"function_docstring" within every
The first statement of a function starts
function can be an optional function_body with a colon (:)
statement - the
documentation string of the
return [expression] and is indented.
function or docstring.
The statement return [expression] exits a function, optionally
passing back an expression to the caller. A return statement with no
Example arguments is the same as return None.
The following function takes a string as input parameter and prints it
on standard screen.
def printme( str ):
"This prints a passed string into this function"
print (str)
return
Unit-IV Functions & Modules
Function Type
There are two types of function in python
• built-in function:
Example: print(), input(), eval().
• User define function :
Example:
def my_addition(x,y):
Sum=x+y
Return sum
There are 68 built-in function version 3.4.
Unit-IV Functions & Modules
Built in Function in Python
Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
Unit-IV Functions & Modules
Built in Function in Python
Function Description
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
Unit-IV Functions & Modules
Built in Function in Python
Function Description
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
Unit-IV Functions & Modules
Built in Function in Python
Function Description
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
@staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip() Returns an iterator, from two or more iterators
Unit-IV Functions & Modules
Calling a Function
Defining a function gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by
calling it from another function or directly from the Python prompt.
Following is an example to call the printme()function −
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("This is first call to the user defined function!")
printme("Again second call to the same function")
Output This is first call to the user defined function!
Again second call to the same function
Unit-IV Functions & Modules
Passing arguments (parameters) to functions
In programming, there are two ways in which arguments can be passed to
functions:
❑ Pass by value:
▪ Function create a copy of variable (Object) passed to it as an
arguments
▪ The actual object is not affected.
▪ Object is of immutable type, because immutable object can not be
modified.
❑ Pass by reference:
▪ The actual object is passed to the called functions.
▪ All the changes made to the object inside the function affect is
original value.
▪ Object is mutable type, as mutable object can be changed, the
passed object are updated.
Unit-IV Functions & Modules
Pass by Reference vs Value
All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within a
function, the change also reflects back in the calling function.
For example −
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: " , mylist)
mylist[2]=50
print ("Values inside the function after change: " , mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: " , mylist)
Values inside the function before change: [10, 20, 30]
Output Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
Unit-IV Functions & Modules
Pass by Reference vs Value
There is one more example where argument is being passed by reference and the reference
is being overwritten inside the called function.
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4] # This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this would
produce the following result −
Values inside the function: [1, 2, 3, 4]
Output Values outside the function: [10, 20, 30]
Unit-IV Functions & Modules
Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where
you can access a particular identifier. There are two basic scopes of
variables in Python −
❑ Global variables
❑ Local variables
Global and Local variables
Variables that are defined inside a function body have a local scope,
and those defined outside have a global scope.
This means that local variables can be accessed only inside the
function in which they are declared, whereas global variables can be
accessed throughout the program body by all functions. When you call
a function, the variables declared inside it are brought into scope.
Unit-IV Functions & Modules
Global vs. Local Variable
Sr.
Local Variable Global Variable
No.
A variable which is declared inside a function is A variable that is declared outside the
1
called as local variable. function is called global variable.
Accessibility of variable is throughout the
Accessibility of variable is only within the
2 program. All functions in the program can
function in which it is declared.
access the global variable.
The local variable is created when the
function(in which it is defined) starts executing The global remains throughout the entire
3
and it is destroyed when the execution is program execution.
complete.
It is preferred as local variables are more It is generally not preferred as any
4 reliable. Because the values cannot be changed function can change the values of global
outside the function. variable.
Unit-IV Functions & Modules
Use of Global Statement
• Global statement is a statement in which a variable is defined with keyword
global.
• The global statement is a declaration which holds for the entire current code
block.
• It means that that the listed identifiers are to be interpreted as global.
• Rules used for global keyword
1) The global keyword is used to use a global variable inside a function.
2) There is no need to use global keyword outside a function.
3) Variables that are not referenced inside a function are implicitly global.
Unit-IV Functions & Modules
Global Statement Example
Without global With Global
a=10 #a is Global Variable a=10 #a is Global Variable
b=20#b is Global Variable b=20 #b is Global Variable
def My_Function(): def My_Function():
a=a+10 global a
print("a= ",a) a=a+10
print("b= ",b) print("a= ",a)
print("b= ",b)
My_Function()
My_Function()
Output: Output:
UnboundLocalError: local variable 'a' a= 20
referenced before assignment b = 20
Unit-IV Functions & Modules
Scope of Variables
Following is a simple example −
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )
Output Inside the function local total : 30
Outside the function global total : 0
Unit-IV Functions & Modules
Return Statement
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.
You can return a value from a function as follows −
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total
# Now you can call sum function
total = sum( 10, 20 )
print ("Outside the function : ", total )
Inside the function : 30
Output
Outside the function : 30
Unit-IV Functions & Modules
Function Arguments
Python provides function calling by using the following types of formal
arguments −
❑ Required arguments
❑ Keyword arguments
❑ Default arguments
❑ Variable-length arguments
Unit-IV Functions & Modules
Function Arguments
Required Arguments:
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error as follows −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme()
Traceback (most recent call last):
File "[Link]", line 11, in <module>
Output printme();
TypeError: printme() takes exactly 1 argument (0 given)
Unit-IV Functions & Modules
Function Arguments
Keyword Arguments:
Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways −
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age = 50, name = "miki" )
Name: miki
Output Age 50
Unit-IV Functions & Modules
Function Arguments
Default Arguments:
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on
default arguments, it prints default age if it is not passed −
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age = 50, name = "miki" )
printinfo( name = "miki" )
Name: miki
Age 50
Output Name: miki
Age 35
Unit-IV Functions & Modules
Function Arguments
Variable-length Arguments:
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are not
named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is given below −
def functionname([formal_args,] *var_args_tuple
):
"function_docstring"
function_body
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call.
Unit-IV Functions & Modules
Function Arguments
Variable-length Arguments: Following is a simple example
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
Output is:
10
Output is:
Output 70
60
50
Unit-IV Functions & Modules
Anonymous (Lambda) Functions
These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
• Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an
expression.
• Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
• Although it appears that lambdas are a one-line version of a function.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Unit-IV Functions & Modules
Anonymous (Lambda) Functions
Following is an example to show how lambda form of function works −
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
Value of total : 30
Output Value of total : 40
Unit-IV Functions & Modules
Introduction to Module
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
Example
The Python code for a module named abc normally resides in a file named [Link]. Here is
an example of a simple module, [Link] −
def print_func( par ):
print "Hello : ", par
return
Unit-IV Functions & Modules
Introduction to Module
Create a Module
To create a module just save the code you want in a file with the file extension .py
Example
Save this code in a file named [Link]
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
[Link]("Rajesh")
Output: Hello, Rajesh
Unit-IV Functions & Modules
Introduction to Module
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Output: 36
Unit-IV Functions & Modules
Introduction to Module
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Example
Import and use the platform module:
import platform
x = [Link]()
print(x)
Output:
Windows
Unit-IV Functions & Modules
Introduction to Module
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Output:
['DEV_NULL', '_UNIXCONFDIR', '_WIN32_CLIENT_RELEASES', '_WIN32_SERVER_RELEASES', '__builtins__',
'__cached__', '__copyright__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__',
'__version__', '_comparable_version', '_component_re', '_default_architecture', '_dist_try_harder',
'_follow_symlinks', '_ironpython26_sys_version_parser', '_ironpython_sys_version_parser', '_java_getprop',
'_libc_search', '_linux_distribution', '_lsb_release_version', '_mac_ver_xml', '_node', '_norm_version',
'_parse_release_file', '_platform', '_platform_cache', '_pypy_sys_version_parser', '_release_filename',
'_release_version', '_supported_dists', '_sys_version', '_sys_version_cache', '_sys_version_parser',
'_syscmd_file', '_syscmd_uname', '_syscmd_ver', '_uname_cache', '_ver_output', '_ver_stages',
'architecture', 'collections', 'dist', 'java_ver', 'libc_ver', 'linux_distribution', 'mac_ver', 'machine',
'node', 'os', 'platform', 'popen', 'processor', 'python_branch', 'python_build', 'python_compiler',
'python_implementation', 'python_revision', 'python_version', 'python_version_tuple', 're', 'release',
'subprocess', 'sys', 'system', 'system_alias', 'uname', 'uname_result', 'version', 'warnings', 'win32_ver']
Unit-IV Functions & Modules
Introduction to Module
from…import statement
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example Output: 36
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
Unit-IV Functions & Modules
Introduction to Module
Python Main Module
• Python module is basically a file containing some functions and
statements
• When Python file is executed directly it is considered as main
module
• The main module is recognized as_main_and provide the basis for
a complete Python program.
• The main module can import any number of other modules. But
main module can not be imported into some other module.
Unit-IV Functions & Modules
Introduction to Module
Modules and Namespaces
• Namespace is basically a collection of different names. Different
namespaces can co-exist at given time but are completely
isolated.
• If two names (variables) are same and are present in the same
scope then it will cause name clash. To avoid such situation we
use the keyword namespace.
• In Python each module has its own namespace. This namespace
includes all the names of its function and variables
• If we use two functions having same name belonging to two
different modules at a time in some other module then that might
create name clash.
Unit-IV Functions & Modules
Example
[Link] [Link]
def display(a,b) def display(a,b)
return a+b return a*b
[Link]
import FirstModule
import SecondModule
print([Link](10,20))
print([Link](5,4))
Output:
30
20
Unit-IV Functions & Modules
Global, Local and Built-in Namespace
• There are three Commonly used categories of namespaces Global namespace,
Local namespace and built-in namespace
• The global namespace contains the module which is currently executing. The local
namespace is a namespace for defining the names in a local function. The built-in
namespace is a namespace in which the built in functionality can be invoked.
import math
def even_number(number): #global namespace
num=number #local namespace
if(num%2==0):
return num
else:
return 0
print( Enter some number)
num=int(input))
if(even_number(num)! =0):
print(The square root of "num, is ",[Link](num)) #built-in namespace
Unit-IV Functions & Modules
Private Variable
• All the identifiers defined in the module are public. That means the
identifier defined in one module can be invoked by other module
without any restriction.
• But there are private variables. The variables that begin with two
underscore (__) are called private variable. These are the variables
which are used only within that module. Other module cannot access
these private variables.
• Even-if we write import " from module name then all the identifiers
except the private variables can be imported.
Unit-IV Functions & Modules
Introduction to Standard Library Modules
Python - Math Module
Some of the most popular mathematical functions are defined in the math module. These
include trigonometric functions, representation functions, logarithmic functions, angle
conversion functions, etc. In addition, two mathematical constants are also defined in this
module.
[Link] , math.e
[Link](), [Link]()
[Link](), [Link](), [Link]()
[Link](), math.log10(), [Link]()
[Link](), [Link]()
Unit-IV Functions & Modules
Introduction to Standard Library Modules
Python - Statistics Module
The statistics module provides functions to mathematical statistics of numeric data. The
following popular statistical functions are defined in this module.
• The mean() method calculates the arithmetic mean of the numbers in a list.
• The median() method returns the middle value of numeric data in a list.
• The mode() method returns the most common data point in the list.
• The stdev() method calculates the standard deviation on a given sample in the form
of a list.
Unit-IV Functions & Modules
Introduction to Standard Library Modules
Python - Collections Module
The collections module provides alternatives to built-in container data types such as list,
tuple and dict.
namedtuple() : The namedtuple() function returns a tuple-like object with named fields.
These field attributes are accessible by lookup as well as by index.
OrderedDict(): The OrderedDict() function is similar to a normal dictionary object in
Python. However, it remembers the order of the keys in which they were first inserted.
deque(): A deque object support appends and pops from either ends of a list. It is more
memory efficient than a normal list object. In a normal list object, the removal of any item
causes all items to the right to be shifted towards left by one index. Hence, it is very slow.
Unit-IV Functions & Modules
Introduction to Standard Library Modules
Python - Random Module
Functions in the random module depend on a pseudo-random number generator
function random(), which generates a random float number between 0.0 and 1.0.
[Link](): Generates a random float number between 0.0 to 1.0. The function
doesn't need any arguments.
[Link](): Returns a random integer between the specified integers.
[Link](): Returns a randomly selected element from the range created by
the start, stop and step arguments. The value of start is 0 by default. Similarly, the value
of step is 1 by default.
[Link](): Returns a randomly selected element from a non-empty sequence. An
empty sequence as argument raises an IndexError.
[Link](): This functions randomly reorders the elements in a list.
Unit-IV Functions & Modules
Assignment No. 4
1. What is the need of function?
2. What is meaning of scope of a variable?
3. Explain Lambda function.
4. What are types of function?
5. How to create a function with arguments.
6. How to call function?
7. What is module and how to create module?
8. Explain any two standard libraries.
9. Explain any four in built function of the python.
Unit-IV Functions & Modules
Unit-IV Functions & Modules