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.
Savitribai Phule Pune University - 2019-20
Need of Function
Function is a block of statements that performs a specific task.
Every function is specified by a name.
Following are reasons we use function in python:
1. All logical related statements are grouped together in one
entity. This makes the program easy to read and understand
and debug.
2. The repetition of code can be avoided
3. Dividing a large program into functions allows us to debug one
at a time then integrate them as whole.
4. Once code of function is written and tested, we can reuse this
code. Reusability is important use of function.
Savitribai Phule Pune University - 2019-20
What is Function
Function is a block of statements that performs a specific task.
Every function is specified by a name.
Collection of function creates a program.
The function is also known as procedure or subroutine in other
programming language.
To use function in program, we need to write following for
function
1. Function definition
2. Function call
3. return statement
Savitribai Phule Pune University - 2019-20
1.Function definition:
The function can be defined using def keyword.
Syntax:
def function_name(parameters):
statement 1
statement 2
return[expression] #return is optional
Ex: def hello_world(): #Function Header
int("hello world") Function Body
Savitribai Phule Pune University - 2019-20
Savitribai Phule Pune University - 2019-20
2. Function Call
In python, a function must be defined before the function
calling otherwise the python interpreter gives an error.
Once the function is defined, we can call it from another
function or the python prompt.
To call the function, use the function name followed by the
parentheses ( ).
We can pass
1) directly value as a parameter
2) a variable
3) An expression
Syntax:
function_name( ) or function_name(var1,var2,…)
Savitribai Phule Pune University - 2019-20
return statement
The return statement is used to exit a function and return value from
where it was called.
A function may or may not return a value.
Syntax:
return[expression]
Program:
def myfunc(name): #Function Header
print(“Hi”, name)
name=str(input("Enter the name:"))
myfunc(name) #Function call
Output: Enter the name : Ayush
Hi Ayush
Write a python program to calculate addition of two numbers
def add(a,b): #Function Header
sum = a + b
print(“Addition of two number is:”,+sum)
a=int(input("Enter value of a:"))
b=int(input("Enter value of b:"))
add(a,b) #Function call
Output: Enter value of a : 4
Enter value of b :16
Addition of two number is: 20
Write a python program to calculate square of given number
using function
def square(num): #Function Header
square=num*num
return square
num=int(input("Enter the number:"))
square(num) #Function call
Output: Enter the number: 4
16
Key Points to remember:
The function name and number of arguments in the function
call must be same as given in function definition.
If by mistake the parameters passed to function are more
than specified function definition, then an error will returned.
Write a python program to perform swapping of two numbers
using function.
def swap(a,b):
a=a+b
b=a-b
a=a-b
print("Value of a is:",+a)
print("Value of b is:",+b)
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
swap(a,b)
Output: Enter the value of a:4
Enter the value of b:5
Value of a is: 5
Value of b is: 4
Function Type
There are two types of function in python.
1. Built in Function:
Example: print( ), input( ), eval( ), range( ).
2. User Defined Function:
Example:
def my_addition(x,y):
sum = x + y
return sum
THERE ARE 68 BUILT-IN FUNCTION VERSION 3.4.
Savitribai Phule Pune University - 2019-20
Savitribai Phule Pune University - 2019-20
Savitribai Phule Pune University - 2019-20
Defining Function
There may be several types of arguments which can be passed at the
time of function calling.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
1. Required arguments
Arguments which are required to be passed at the time of function
calling with the exact match of their positions in the function call and
function definition.
If either of the arguments is not provided in the function call, or the
position of the arguments is changed, then the python interpreter will
show the error.
def func(name): def calculate(a,b):
message = "Hi "+name; return a+b
return message; calculate(10)
name = input("Enter the name?")
print(func(name)) Output:
Output: calculate() missing 1
Enter the name? akshay required positional
Hi akshay argument: 'b'
2. Keyword arguments
Keyword argument is also called as named arguments.
These are arguments in which value is associated with the names.
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.
def data(name, course): def data(name, course):
print("name is:",name) print("name is:",name)
print("course is ",course) print("course is: ",course)
data(name="Sakshi",course="Python") data(course="Python",name="Sakshi")
Output: Output:
name is: Sakshi name is: Sakshi
course is: Python course is: Python
Example:
#The function simple_interest(p, t, r) is called with the keyword
arguments the order of arguments doesn't matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))
Output:
Simple Interest: 1900.0
def interest(p,t,r):
return (p*t*r)/100
print("Simple Interest:“,interest(time=10,rate=10,principle=1900))
Output:
simple_interest() got an unexpected keyword
argument 'time'
Savitribai Phule Pune University - 2019-20
Savitribai Phule Pune University - 2019-20
3. Default arguments
Default value indicates that the function argument will take that value if no
argument value is passed during function call.
The default value assigned by using assignment (=) operator.
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
Output:
My name is john and age is 22
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
printme(age = 10,name="David")
Output:
My name is john and age is 22
My name is David and age is 10
Savitribai Phule Pune University - 2019-20
Savitribai Phule Pune University - 2019-20
4. Variable length Arguments
The variable length argument is very useful when do not know exact
number of argument passed to function
*args in function definition used to pass variable number of arguments to
function.
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("john","David","smith","nick")
Output:
type of passed argument is <class 'tuple'>
printing the passed arguments...
john
Lambda or Anonymous Function
Lambda function is anonymous function.
anonymous function is a function that is defined without a name.
normal functions are defined using the def keyword, in Python
anonymous functions are defined using the lambda keyword.
Syntax:
lambda arguments: expression
Lambda functions can accept any number of arguments, but they can
return only one value in the form of expression.
Ex:
x = lambda a:a+10 #a is an argument and a+10 is an expression
print("sum = ",x(20)) #which got evaluated and returned.
Output: sum = 30
Ex:To perform addition of two number
add = lambda a, b :a+ b
print("sum = ",add(20,10))
Output: sum = 30
Use of Lambda function:
1. The lambda function is used when we require a function without any
name for very short span of time.
2. The lambda function is used when we want to use some anonymous
function inside another function.
Ex: def myfunc(n):
return lambda a : a ** n
x=myfunc(3)
print(x(2))
Output: 8
Savitribai Phule Pune University - 2019-20
Variable Scope and life time
Scope of variable means – the part of program in which a variable is
accessible.
Lifetime of a variable means – duration for which the variable exist.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global
scope whereas the variable defined inside a function is known to have a
local scope.
Example:
a=10
def my_func(b):
global a
sum=a+b
print("value of a local is :",+a)
print("sum is :",sum)
my_func(20)
print("value of a global is:",+a)
Output:
value of a local is : 10
sum is : 30
value of a global is: 10
Example:
a=10 #Global Variable
def my_func(b): # b is local variable
a=30 #a is local variable
sum=a+b #sum is local variable
print("value of a local is:",+a)
print("sum is :",sum)
my_func(20)
print("value of a global is:",+a)
Output:
value of a in local is : 30
sum is : 50
value of a global is: 10
global statement
Use of global statement:
Global statement is a statement in which a variable is defined with
keyword global.
we can use global variable in local block using global keyword.
Rules used for global keyword
The global keyword is used to use a global variable inside a function.
There is no need to use global keyword outside a function.
Example:
a=10
def my_func(b):
sum=a+b
print("value of a local is :",+a)
print("sum is :",sum)
my_func(20)
print("value of a global is:",+a)
Output:
UnboundLocalError: Local variable ‘a’ referenced before
assignment
To avoid this we use global keyword
Documentation string (docstring)
Python documentation strings (or docstring) provide a convenient way of
associating documentation with Python modules, functions, classes, and
methods.
docstring is same as comment statement.
docstring are important as they help tools to automatically generate
online or printed documentation.
It is easy for users to understand code.
In program, we write comment, docstring in program, We can access the
docstring using print( )
Documentation string (docstring)
Rules for using Documentation string:
1. It should be declared using triple double quotes( “ “ “ “ “ “)
2. It should begin with capital letter and end with period (.)
3. The first line should be a short description.
4. If there are more lines in the documentation string, the second line should
be blank, visually separating the summary from the rest of the
description.
Syntax:
def function_name(parameters):
""" document string explaining function """
function body
return [expression]
To access docstrings in program we use the __doc__ method in print
statement
def function_name():
""" Hi """
print(function_name.__doc__)
Output: Hi
def myfunc():
""" This function is for addition of two numbers
Two numbers are read, added and result
is displayed."""
a=int(input("Enter value of a"))
b=int(input("Enter value of b"))
c=a+b
print("result is",c)
print(myfunc.__doc__)
myfunc()
Output:
This function is for addition of two numbers
Two numbers are read, added and result is displayed.
Enter value of a4
Enter value of b5
result is 9
Good Programming Practices:
To achieve readability of large and complex program, we have to follow
good programming practices. We have to follow some standard rules
while writing python programs.
1. Make use of meaningful variable names
2. Insert blank line to separate functions, classes and the statements inside a
function
3. Use indentation in program
4. Use appropriate comments in your program so that program is readable
and understandable.
5. Use documentation string to explain more about function
6. Use spaces around operators.
7. Function name should be written in lowercase letter
8. The class name having first letter should be capital letter
ex: class MyDemoClass
Introduction to module:
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your
application.
1. Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Ex:Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Now we can use the module we just created, by using the import
statement:
Ex: Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Akshay")
Output:
Hello Akshay
2. Variables in Module
The module can contain functions, but also variables of all types (arrays,
dictionaries, objects etc):
Ex: Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:
Ex: import mymodule
a = mymodule.person1["age"]
print(a)
Output: 36
Re-naming a Module
You can create an alias when you import a module, by using the as
keyword:
Ex:Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Output:
36
3. from ….import statement
There are many variables and functions present in module. we use them
using import statement.
Ex:
from math import sqrt
print(“Square root of 25 is:”, sqrt(25))
Output:
5
4. Name of module
Every module has name.
One can use name of module using __name__ attribute of the module.
Ex: module3.py
print(“Welcome”)
print(“Name of module is :”, __name__)
Output:
Welcome
Name of module is : __main__
5. The dir( ) function
The dir ( ) function is an inbuilt function.
It is used to display functions, variables or classes used in modules.
Ex: Mymodule.py
def display(user):
print(user)
user=”Admin”
display(user)
print(dir())
Output:
Admin
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__',
'__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1',
'_ih', '_ii', '_iii', '_oh', 'display', 'exit', 'get_ipython', 'quit',
'user']
Introduction to packages
Packages are namespaces which contains multiple packages and
modules. They are simply directories.
A directory must contain a file named __init__.py for package.This file
can be left empty but we generally place the initialization code for that
package in this file.
The package can be nested to any depth having their __init__.py file.
To create package called MyPackage, First create a dictionary called
MyPackage having module MyModule.py and empty __init__.py file.
To use MyModule in program, you must first import it. This can be done
in two ways.
import MyPackage.MyModule
Or
from MyPackage import MyModule
Ex:
import random
for i in range(10):
value = random.randint(1,100)
print(value)
Output:
57 18 58 42 38 80 84 89 18 71
Introduction to standard library modules
Python supports three types of modules
1.modules written by programmer
2.modules that are installed from external sources
3.modules that are pre-installed with python.
Modules that are pre-installed in Python are together known as standard
library.
Some useful modules in standard library are
string, re, datetime, math,random, os,
multiprocessing, subprocess, socket, email,
json, doctest, unittest, pdb, argparse, sys.
You can use these modules for performing tasks like string parsing, data
serialization, testing, debugging and manipulation dates, emails,
command line arguments, etc.